Can We Just Talk? Script Communication in Unity using GetComponent

I think Script Communication is one of the harder concepts to grasp when starting out with Unity and one I will continue to come back to. In this article, I am going to be go over how to use GetComponent to access another script when to Game Objects collide.

In this Game Scene, I have two Game Objects with their own scripts that need to communicate. We have the Player script and the Enemy script. The Enemy script is detecting the collision between the two Game Objects using OnTriggerEnter and recognize the player by using a tag.

Collision Detection on Enemy Script

When this collision occurs, the player needs to lose a life but this method is on the Player script and not the Enemy script. So, the Enemy script needs to let the Player script know when the collision happens to use to PlayerDamage method. How can we make this two scripts talk to each other?

PlayerDamage method on Player script

In the OnTriggerEnter2D, what object the Enemy is colliding with is stored inside the variable other.

When the Enemy collides with the Player, that variable stores the reference to the Player that we can now access. We can access the Player script by making a local variable of kind Player and assigning it to other.GetComponent<Player>(). This grants the Enemy script access to the Player script and any public methods it may have.

Using GetComponent to access the Player Script

Now we can call the PlayerDamage method on the Enemy script, so a life is taken every time a collision between the two happen until the Player is out of lives and destroyed (null).



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