Basic Communication Between Classes

by Lance Gold

Here is the short version of last year's lengthy git instruction:

Return to index

Unity gameObjects need to tell each other to go or stop.

In this example, we have a Player with points that needs to tell an Enemy to stop.

In the Enemy’s parent class “SpawnManager”:


public class SpawnManager : MonoBehaviour
{
    private bool _stopSpawning = false;
...
    IEnumerator SpawnRoutine(float waitTime)
    {
        while (_stopSpawning == false)
        {
            // instantiage Enemy

        }
    }

    public void OnPlayerDeath()
    {
        _stopSpawning = true;
    }
}

In the Player class, not yet connected:


public class Player : MonoBehaviour
}
    private int _lives = 3;
...    
    public void Damage()
    {
        _lives -= 1;

        if(_lives < 1)
        {
            Destroy(this.gameObject);
        }
    }
}

from the Unity Scripting API:

GameObject.GetComponent

Declaration

public Component GetComponent(Type type);

Parameters

type— The type of Component to retrieve.

Description

Returns the component of Type type if the game object has one attached, null if it doesn't.

Unity — Scripting API: GameObject.GetComponent

(a) We create a variable to store the reference of the component,

(b) In Unity’s “public void Start()” we assign the reference to the component in the other class. We find the component type we are looking for and assign it to that variable type.

(c) Check if the return is “null” (if the component exists).

(d) Use the reference.

Our Player and Spawn Manager example

We need out Player class to find our SpawnManager class.

Spelling of Spawn_Manager and SpawnManager component in Inspector

Spelling of Spawn_Manager and SpawnManager component in Inspector

Use the same spelling as in the Inspector and Hierarchy.


public class Player : MonoBehaviour
{
    private SpawnManager _spawnManager;
...
    void Start()
    {
        // find gamecomponent and assign type
        _spawnManager = GameObject.Find("Spawn_Manager").GetComponent(); 
    }
}

next step is a null check before variable use.


...
    void Start()
    {
        _spawnManager = GameObject.Find("Spawn_Manager").GetComponent(); 
        if(_spawnManager == null)
        {
            Debug.LogError("Spawn_Manager.SpawnManager is missing.");
        }
...
    }

Communication is established, so use connection in code


public class Player : MonoBehaviour
{
   public void Damage()
   {
...
      if(_lives < 1)
      {
         // call method to stop spawning Enemys
         _spawnManager.OnPlayerDeath();
...
      }
   }
}