Communication in Unity using GetComponent

Kinga Osińska
2 min readApr 9, 2021

Script communication is one of the things that you will do in every game.
For example, you will need this to tell another script that handles enemies spawning that your Player is dead, or to change material color.

To access a component you will need to use “GetComponent”

A simple example with getting access to another script on the same GameObject:

We have a GameObject that has two scripts attached: “FirstScript” and “SecondScript”. SecondScript has a variable “lives” that we want to access.

First, we need a reference to the SecondScript. Reference to SecondScript is a variable of the type of the name of the script.

Next, we will initialize our variable with GetCompoenent. It is a good practice to use GetComponent is Awake() or Start() method, or only once when is first needed.

Now we can access “lives” variable:

What if the SecondScript is on a different GameObject?

If the script you want to access is on a different GameObject, then you need to find this GameObject first:

--

--