Getting Components with GetComponent

Rook Sullivan
Apr 7, 2021

--

I want my Enemy objects to be able to tell the Player object to subtract a life on contact. However, the Enemy object doesn't have access to the _lives variable stored on the Player.

Within the Player script, I created a public method Damage() that when run, causes the Player to lose a life. I then needed to give the Enemy a way to access that method. That is where GetComponent comes in. By calling on GetComponent<Player>, the Enemy has access to the Player script located in the Player object. We can then tell the Player script to run the Damage() method on collision. Once the player object has lost all three lives, it is destroyed.

--

--

Rook Sullivan
Rook Sullivan

Written by Rook Sullivan

Non-binary game dev sharing my experiences in Unity.

No responses yet