Communication Between Scripts in Unity Using GetComponent

At some point in using Unity you will probably want two of you objects to communicate to each other. To do this you will need to use GetComponent. In this example we will use the case of an enemy running into the player and being able to damage and destroy the player. In the example the enemy has an event trigger for when they collide. In the event trigger for the enemy you are going to access the Player component and call the Damage function below to reduce the players lives. Remember to make the function you want to use public so it can be accessed.

public void Damage()
{
_lives--;
if (_lives < 1)
{
Destroy(this.gameObject);
}
}

You can access the Player component in the event trigger through the transform of the other variable. GetComponent is a function of transform. You then put the component that you want to get in between < and >. After the GetComponent function you can call the functions from the component. Below you can see it used to call the Damage function.

other.tranform.GetComponent<Player>().Damage();

Directly calling the function directly like the above example however can leave you exposed to potential errors if there is no Player component found. Because of this it is safer to create a variable and assign the component to it and then check that it is not null. This will protect your game from errors due to not finding the component. You will then be able to use the variable to access the Damage function like in the example below.

Player player = other.transform.GetComponent<Player>();
if (player != null)
{
player.Damage();
}

Now your enemy is using GetComponent to be able to communicate and interact with the Player!

Good Luck Adventurer!

-Chris