The training program through GameDevHQ introduces a concept fairly early on regarding script communication. Essentially to create the expected actions and behaviors in a game or application, we can program the methods and functions to interact with one another and share information (booleans, variables, health, damage, attack), and/or initiate functions in other methods.
The scenario in the training module is as follows:
- Gameplay begins, and the Spawn Manager spawns enemies.
- Player is moving around the scene destroying enemy prefabs, while trying to avoid collisions with the enemy prefabs.
- If the Player collides with the enemy prefabs, the Player takes damage(← script communication), and the enemy prefabs are destroyed.
- If the Player loses all the health / lives, the Player is destroyed, and we need to make the Spawn Manager stop spawning (← script communication).
So we have the Spawn_Manager game object that needs to interact with the Player game object, and the Enemy game object needs to interact with the Player game object.
In the Player C# script, we can create a reference to the Spawn_Manager game object so we can get access to the SpawnManager class. The reference is done in void Start: set the local variable equal to a GameObject.Find(“exact name of game object”).GetComponent<SpawnManager>(); There is a null reference check after in order to check if this game object was successfully found (i.e., in case you mistyped something or misspelled something).
Another approach to creating a reference to another game object is to create your own tag for the Spawn_Manager, similar to the “Player” tag, and search for that by FindGameObjectwithTag(_____).
Over in the SpawnManager class, we create a public void function OnPlayerDeath() that contains a bool that we change to true if the Player dies. This bool is checked in the coroutine that keeps the enemies spawning. Note the function is public in order to be accessible outside of this class.
In the Enemy C# script, if the Enemy collides with the Player, we get a reference to the Player game object and Player class. Similar to the above example, we include a null check to confirm we have successfully found the Player game object, and we reference the Player class which has a Damage function.
Back in the Player C# script, we can see the public void function Damage, which was referenced in the Enemy script. In this function, if the Player loses all their lives, we reference the SpawnManager class which has a function OnPlayerDeath to set that to true, which stops the spawning of enemies.
I appreciate you stopping by.