Script Communication in Unity is modifying one script from another, and this modification can be the calling of methods, changing of variables, or even the deactivation of the other script.
One way to do this is using the GetComponent method to retrieve the desired component on a gameobject. A component is what Unity uses to define anything that is on a gameobject, whether it is a script, Collider, rigidbody, mesh, renderer, and so on.
The most common way to use GetComponent is to store the retrieved component inside of a variable. What is between the < > is the type of component you are retrieving (i.e., script’s class name).
In the last article, we created an Enemy to destroy. To show how to use GetComponent, we will create a simple health system so the Enemy can damage the Player. First, go to the Player script and add a private int variable named “_lives” with a value of 3.
Next, since _lives is private, we need to make a way for other scripts to adjust it. To do this, create a new public method named “ChangeLives” and take in an int called “amount”. Then inside of the method, add amount to _lives, check if _lives is less than 1 and if it is, then Destroy the Player.
Make sure to Tag the Player gameobject with the “Player” tag. Tagging the Player will help us to identify the Player gameobject easily in the other script.
In the Enemy script inside of OnTriggerEnter, make an if statement that checks if the Collider that entered the Enemy gameobject’s trigger volume has the Tag “Player”. Inside of the if statement, make a local variable of type Player named “player” and have it equal to the other Collider’s Player script component. Then make an if statement to make sure that player is not equal to null (nothing); this is called null checking and is an excellent habit to get into. Inside the if statement, call the ChangeLives method from player and pass in -1 as the amount. Finally, have the Enemy Destroy itself.
Now copy the Enemy a couple of times and enter Play Mode. The Player should take three collisions before it is destroyed.
Till next time, good luck and happy coding!