Using Coroutines to Control Our Enemy Spawn Manager in Unity
Objective: To understand how Coroutines work and implement an Enemy Spawn Manager using Coroutines.
Now that I have got the collisions set up, it’s time to have our enemies spawning consistently and on a timer. This is where Coroutines shine!
What is a Coroutine?
A coroutine is a function that can suspend (yield or pause) its execution until the given yield instructions have finished.
Using a Coroutine In Our Game
Moving on from simply having 1 enemy in the game, I would like to have them consistently spawning on a timer until our player has either completed a wave or died. In order to get this setup let’s have a look at some code.
First of all we need to create a new script called ‘SpawnManager’ and we are going to attach it to an empty game object that is in our scene in the Hierarchy with the same name:
Now, we are going to add some code to that script and see the comments for the breakdown:
Don’t forget to drag the Enemy prefab into the newly created variable in the Inspector:
Now, the SpawnEnemiesRoutine() method that has been setup will only run once through as we are missing something. First of all let’s see if our Enemy will spawn if we hit Play:
Now we want the enemies to continually keep spawning while the player is alive. That’s it, we are going to use a while loop.
In our case, we are going to use a Boolean as a trigger switch to tell our Coroutine to stop running when this trigger switch is true. Be careful with while loops as you can get yourself into a dangerous endless loop which could freeze and crash your game and any unsaved work along with it.
We are still missing the trigger switch method that is going to shut this all down when our player’s lives have reached zero. Still within the SpawnManager script add the following method():
Now, within the Player script let’s access this OnPlayerDeath() method so we can can tell the SpawnManager script when our Player’s lives have reached zero.
Let’s hit Play and watch them continually spawn in!