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:

Spawn Manager game object with a spawn manager script attached

Now, we are going to add some code to that script and see the comments for the breakdown:

Creating our timed spawning enemies

Don’t forget to drag the Enemy prefab into the newly created variable in the Inspector:

Drag the enemy prefab into the Enemy Prefab 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:

Success!

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():

Public OnPlayerDeath() method for our script communication to the Player script

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!

It’s raining enemies

Useful Links:
https://docs.unity3d.com/ScriptReference/Coroutine.html

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store