Unity: Communicating between scripts with GetComponent
As much as we’d like pure OO programming, inevitably you’ll need one script to access another. Here’s how to do it in Unity with GetComponent.
The hierarchical nature of Unity makes it easy for one script to access a component of a particular object. For instance, in a player-lives system, we need to tell the player to lose a life from outside the player script.
In this simple damage method in the player script, we remove a life, print the amount of lives to the console, then check if the lives drop below one (player destroyed). Note that this method is public; this allows other scripts to call it.
In Unity we have assigned the ‘Player’ tag to the Player gameObject.
Jumping over to our enemy script we have created the OnTriggerEnter method which returns ‘other’. We can use this to access the other gameObject.
Here we check if the tag attached to ‘other’ is ‘Player’. If so, we create the variable ‘player’ which is of type Player. This type comes from the name of script or component we are looking to access. We assign the Player component to the variable using GetComponent.
As a precaution against errors, we null check that the Player component exists before we try to access it. If it is not null, we then use player.Damage() to call the Damage method in our Player script.
Finally, we destroy the enemy gameObject.
You can access any component in this way, not just scripts. You could, for example, use GetComponent to change an object’s colour via the material component.