Script Communication in Unity using GetComponent

Script communication in Unity is used to modify one script from another. You can call methods, update variable or even deactivate a script.

One way to accomplish this is to use the GetComponent method to access the component of the game object. A component is anything that is attached to the game object, i.e Rigidbody, Collider, Scripts. In this article we will focus on assessing the Script component.

Get Component

I will show 2 examples of using the GetComponent method. The first is to create a variable for the component type and add a tag to the game object so it can be used in the game object find with tag. The second is to create a variable for the component type in the On Collision method and use the other variable from an On Trigger Method.

adding a tag
Get Component

In both of these examples and as a best practice you should perform a null check, this will eliminate errors during runtime if the object is not found.


Update the player lives when damaged by the enemy. Subtract a life for every enemy attack


First, we need to make sure the Tag is set to “Player” on the Player Game Object. This is shown above. Next, we will need to create a variable on the player to store the number of Lives.

Variable for player lives

Then we will want to create a Method in the Player script to subtract 1 from the Variable Lives and also destroy the Player when lives reach zero. In our Space Shooter Game, I will name the Method “Damage”

Damage Method

Next, we will access the Player script from the Enemy. I will use the example from above of using the GetComponent method inside the OnTriggerEntger Method using the variable other. The other variable stores the game object that collided with the Enemy.

Demo of Script Communication

Notice when the player is hit by the enemy, the lives are decreased by 1.

Till next time , Happy Coding

Unity / C# Game developer