2D Shooter: Stopping a Swarm when the Player Dies

We can spawn enemies every five seconds, and we can keep them organized in the hierarchy, now its time to add a way to stop the spawning when there is no player around to shoot them. We’ll be having to work more with GetComponent, and more specifically, GameObject.Find.

First, we need to create a global bool variable that’s false. In my article about creating the spawn system this was _stopSpawning. This is the condition in the while loop that keeps the loop going as long as it is false.

Next, in the script for SpawnManager, we need to create a public method that will change the bool variable _stopSpawning to “true” so the loop will cease.

Now we need to move to the player script so we can create a way for it to be initialized when the player dies.

For us to call it up later we need to create a global SpawnManager variable. Like this:

Now we need to tell the program to find the SpawnManager object, and assign that information to the variable. We should also make sure that it’s finding the object and the script by testing it with an if statement.

If it doesn’t work, Unity will let us know.

Now all that is left to do is call up the OnPlayerDeath() method in the player script, in the method where we created a life system. When the player’s life reaches zero, we want it to initialize OnPlayerDeath, thus turning _stopSpawning to true and making the spawn loop obsolete.