Unity Guide

Script communication in Unity | GetComponent

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

: 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 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 methodinside 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 classscriptas the component, we can get access to the 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 or visit my :D



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Fernando Alcantara Santana

Fernando Alcantara Santana

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