My journey becoming a Unity game developer: Script Communication in Unity using GetComponent. Using a Spawn Manager for Galaxy Invaders pt.3
Objective: Make the enemies stop spawning after the player dies. Use the Component GetComponent<> to communicate between the Spawn Manager and PlayerBehavior scripts to stop spawning enemies.
Let’s begin with the SpawnManager script, and create a new Private Type Bool name _stopSpawning. Set its value to False as the game will spawn enemies right from the outset.
In the coroutine SpawnRoutine(), change the WHILE() condition to _stopSpawning equals False. This condition will keep the enemies spawning as long as this condition is false.
Now we need to find a way to change the _stopSpawning variable to True. It’s not good practice to change a variable’s value directly inside of a script. Instead, we’re going to change the value inside a method which is less problematic.
Create a new Public Type Void, since we don’t need a return type result name OnPlayerDeath(). Inside the OnPlayerDeath() method, set the _stopSpawning variable to True so when this method is called, enemies spawned will be deactivated.
Now we’re going to use a technique called Script Communication. This technique allows us to access properties and methods from a component that is attached to a game object through a script. There are 3 steps in using Script Communication with the 1st step is creating a variable to serve as a handle to the component you need access to. The 2nd step is to assign the variable to Get the Component you need to use. The 3rd step is to use the variable to retrieve properties and methods that you want to use from the chosen component.
Over in the PlayerBehavior script, create a Private Type SpawnManager name _spawnManager. This variable will be used to communicate with the SpawnManager script.
Inside the Start() function, set the _spawnManager variable to Find the Game Object name “Spawn Manager”, and Get the SpawnManager script Component.
Then inside the Damage() method, use the _spawnManager variable to call the OnPlayerDeath() method to signal the game to stop spawning enemies.
To be on the safe side, inside the Start() function add an IF condition to NULL check if the _spawnManager is active. If the _spawnManager is NULL, use the Debug.LogError with a message to let the designers know about this problem.
Play the game, notice that when the player dies the Enemy Container will have the amount of enemies onscreen when the player dies. You will see the same amount of enemies without any new enemies spawning even though the game is still active.