Script Communication in Unity using GetComponent
Script communication in C# refers to the ways different scripts or components within a program interact with each other. In game development, this is especially important because scripts often need to “talk” to each other — sharing information, requesting data, or triggering actions between components.
One of the most commonly used ways to achieve script communication in Unity is through GetComponent<>(). In Unity, the GetComponent<>() method is used to obtain a reference to a specific component attached to a GameObject. This is crucial when you want to interact with or modify that component’s properties and behaviors during runtime.
Get JUMAMUROD ARALOV’s stories in your inbox
Join Medium for free to get updates from this writer.
We have a simple game where the Player moves around and tries to avoid the Enemy.
- When the enemy collides with the player, the player should take damage.
- The damage logic (reducing health and checking if the player should be destroyed) is written inside the Player script.
- The enemy’s responsibility is only to detect the collision and then “ask” the player script to apply damage.
This is where GetComponent<>() comes in — the enemy script can find the Player component on the collided object and call its Damage() method.
Player Script
public void Damage()
{
_lives = _lives - 1;
Debug.Log("Player is Damaged by 1!");
//check if dead //destroy us
if (_lives < 1)
{
Destroy(this.gameObject);
Debug.Log("Player is Dead!");
}
}Enemy Script
private void OnTriggerEnter(Collider other)
{
//if Enemy hits the Player
if (other.CompareTag("Player"))
{
//Damage player
Player player = other.transform.GetComponent<Player>();
//Check for NULL
if (player != null)
{
player.Damage();
}
//Destroy Enemy (us)
Destroy(this.gameObject);
}
}- The Enemy script doesn’t know how the player’s health works; it just calls Damage() on the Player script.
- The Player script manages its own health and decides when to destroy itself.
When we write:
Player player = other.GetComponent<Player>();Unity will try to find the Player script on the object we collided with. If it exists, Unity gives us a reference to it. If it does not exist, Unity returns null.
That is why we check
if (player != null)This check makes sure the script actually exists before we try to use it. If we skip this step and the component is missing, the game will throw a NullReferenceException error and stop running that code.
The null check is basically a safety step. It prevents the game from crashing if the object we hit has the “Player” tag but does not have the Player script attached.







