Script Communication in Unity using GetComponent

Simon Pham
2 min readJun 24, 2023

Objective: The goal of this blog post is to provide you with guidance on how to use GetComponent to facilitate script communication in Unity.

Script communication can be a little bit confusing, especially if you’re new to Game Development in Unity, but it doesn’t have to be scary. In Unity, a script is considered a custom component, and it has to be attached to a GameObject. Often, you might need to obtain some information from another script that is attached to a different GameObject. One of the most common approaches to do that is using GetComponent.

To get access to a component, you will first need access to its GameObject and then use the GetComponent on that GameObject. For instance, we have a player and an enemy, and in the player script, we have a function called Damage that subtracts one life from the player every time it collides with the enemy. If the player has no lives left, it destroys the player object:

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

On the other hand, we need to destroy the enemy every time it collides with the player object and call the Damage function inside the enemy script. So how do we achieve this?

Well, we will first need to set up a collision system for the two GameObjects, and if you’re not sure how to do that, check out my Day 7 blog post. Here’s our setup:

private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
// we destroy the enemy
Destroy(this.gameObject);

// we call the damage function on the player
}

}

Currently, every time the enemy collides with an object and if the tag of that object is “Player,” we call the Destroy method on the enemy object. The “other” object now has the information about our player object, which we can use to access the Player component in our player object.

Player player = other.GetComponent<Player>();

Here, we use GetComponent on the “other” object (aka the player object in this situation) and specify that we want to get the “Player” component. We store that information in a variable called “player” with the variable type as Player.

The next step is to null check our component to make sure we actually have access to it:

if (player != null)
{
Debug.Log("The player component is not null");
}

Once we confirm that the message is logged into the console, we can replace it with the Damage function:

if (player != null)
{
player.Damage();
}

And here is the final code:

private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
Destroy(this.gameObject);
Player player = other.GetComponent<Player>();
if (player != null)
{
player.Damage();
}
}
}

--

--