Unity Guide

Script communication in Unity | GetComponent

A quick guide about how to implement script communication in Unity using the GetComponent method

Fernando Alcantara Santana
3 min readMay 11, 2021

--

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:

We can use [SerializeField] to test the amount of lives in the inspector.

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):

A life will be subtracted every time the function is called and, if there’s less than 1, the player gets destroyed.

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.

It’s important to verify that the component we get isn’t null to avoid a compile error when calling GetDamage.

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:

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.

If you want to know more about me, feel free to connect with me on LinkedIn or visit my website :D

--

--

Fernando Alcantara Santana

A passionate computer technology engineer and Unity developer that is always looking to grow in every aspect of life :).