Script communication in Unity | GetComponent
A quick guide about how to implement script communication in Unity using the GetComponent method
Objective: Implement script communication using GetComponent to damage a player every time it collides with an enemy in a space shooter game in Unity.
Following with the development of the space shooter prototype, it’s necessary to implement the destruction of the player’s spaceship after being destroyed by the enemy attacks. So, to start, we need to open the player’s script and create a variable to store the amount of lives that the player will have:
Then, in order to destroy the player when it loses all his lives, we need to create a public function (that can be called from outside the class):
Now, to communicate with the enemy script, we need to use the GetComponent method inside the enemy script. By using this method with the colliding gameobject, we can get access to the components attached to it. So, by choosing the Player class script as the component, we can get access to the GetDamage function of the player script.
Finally, if we run the game in Unity, we’ll see that the lives are subtracted when the player collides with the enemies and then it gets destroyed after 3 collisions:
If you want to know more about this function, visit the Unity documentation:
Suggest a change Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all…
And that’s it, you can communicate between scripts in Unity using GetComponent! :D. I’ll see you in the next post, where I’ll be showing how to use coroutines in Unity to spawn infinite enemies in the game.