Script Communication in Unity using GetComponent

James Hills
2 min readJan 23, 2024

Often times, one or more scripts in Unity need to communicate with one or more others scripts. Below, I’m going to show you a few simple steps on how to get scripts to communicate with GetComponent.

For an example, if you had an enemy object collide with the player object, you would expect some type of damage to one or both objects. Within a script, “Enemy.cs”, which is attached to your enemy object, you can access components of the player object. In this example, we want to access the “Player.cs” script, which is attached to the player object, via the “Enemy.cs” script.

First, we need to create a variable to hold the information we get from the “Player.cs” script.

private Player _player;

Then, we would need to use GetComponent to access the Player object.

 _player = GameObject.Find("Player").GetComponent<Player>();

Once we’ve accessed the object, it’s good practice to do a null check when trying to access a component from another object, just to ensure it does exist. Then we would check to see if the object colliding with the enemy is Player. If it is Player, then we call the Damage() method from the “Player.cs” script and if you have a method to destroy the Enemy on collision, you would call the EnemyDestroyed() method, or whatever name you may have givin the method.

private void OnTriggerEnter2D(Collider2D other)
{
if (_player != null) // If the player is not null
{
if (other.CompareTag("Player")) // and the tag of the object is "Player"
{
_player.Damage(); // then damage the player
EnemyDestroyed(); // and destroy the enemy
}
}
}

Now when the Enemy and Player collide, the player will take damage and the enemy is destroyed.

Thank you for taking the time to read this short, informative article. Please check out some of my other articles.

--

--

James Hills

I am a married father of 5 children. I decided at 13 years of age that I was going to become a Software Developer.