GetComponent to get communication — Unity3D
C# Scripts are components of game objects. To communicate from script A to script B, A must first store in a variable the transform (Game Object) that holds script B to GetComponent<scriptB>.
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
//this next line defines the "other" var through trigger collision
Player player = other.transform.GetComponent<Player>();
if (player != null )
{
player.Damage();
}
}
}
In this case, script A is an Enemy.cs getting the script B component through trigger collision and the tag detection. When the enemy hits the player, Enemy.cs calls the player.damage() method inside the Player.cs.
To Find another game object and its components without collision, this method: GameObject.Find(“Name_As_In_Hierarchy”).GetComponent<…>();
private SpawnManager _spawnManager;
void Awake()
{
_spawnManager = GameObject.Find("SpawnManager").GetComponent<SpawnManager>();
if(_spawnManager == null)
{
Debug.LogError("The Spawn Manager is NULL");
}
}
public void Damage()
{
_currentHealth -= 20;
if (_currentHealth < 1)
{
_spawnManager.OnPlayerDeath();
Destroy(this.gameObject);
}
}
This is the Player.cs storing a private global variable for the spawn manager. When starting the game, the SpawnManager.cs is found inside the SpawnManager game object in the Hierarchy, checked for a null error, and when the player’s current health is 0, the Player.cs calls _spawnManager.OnPlayerDeath() method inside the SpawnManager.cs to stop spawning enemies when the player dies.
More on GetComponent — Unity Manual.