Unity Script Communication with GetComponent

Damian Dąbrowski
2 min readMay 12, 2021

--

The only component in Unity that you have direct access to, is the Transform of an object. With Transform component and GetComponent method we can communicate between scripts.

Let’s take as an example a player who has 3 lives, if he collides with an opponent the life value will drop by 1, if the value reaches 0, the player dies. We will need an integer value for life and a Damage() function.

In the Enemy class we will check if there was a collision or not, if so, we will need to access from our Enemy class to the Damage() function of the Player class. How can we do this?

We can access the Player class with the Transform component and GetComponent and the help of OnTriggerEnter method. Let’s read the below code.

OnTriggerEnter checks if there has been a collision between the Enemy object and another object, if so, the colliding object will be stored as the variable “other”.

Next, we check if the object is indeed our player, if so, we create a player object which we link to the player class via the Transform component and the GetComponent method. This way, we have access to the player and can call the Destroy() method.

Unity offers several ways to communicate between scripts, and using GetComponent is one of them.

--

--

Damian Dąbrowski
Damian Dąbrowski

Written by Damian Dąbrowski

Hi, I’m Damian, an Electrical Power Engineer, who loves building AI powered apps.

No responses yet