Day 13: Script Communication in Unity using GetComponent

Tyler Smallwood
2 min readMay 5, 2021

Now that we have an understanding on physics, we will continue on the game and talk about script communication.

On our enemy script we will add a OnTriggerEnter() to cause damage to the player and Enemy. In OntriggerEnter we will check to see who has entered the trigger area, the player or Laser. So on the Laser and Player Object we need to give them the correct Tag.

Now that they have the correct tag we check in the script by using compareTag().

Now to destroy the Enemy object, and the laser.

Now to cause damage to the player, On the player script we need to create a public function that subtracts lives every time it’s called.

Now that we have a function that damages the player and destroys the player when lives is less than 1. We need to call a reference to the player on the enemy script. We will do a null check to make sure we don’t get an error.

We do other.GetComponent<Player>() to get the Player script and access any public variable or function that is on the Player script.

Now to call the public function damage on the player.

And there we go. Our enemy script will get destroyed when it runs into the player or laser. If it is the player, it will communicate with the Player script using GetComponent<>(), to damage the player until the player dies.

--

--

Tyler Smallwood

I am passonate on learning to program and use Unity to become a skillful Unity Developer