Coroutines: Setting up an enemy spawner and keeping it clean(Game Dev Day 13)

A coroutine is a loop that will run in its entirety before rerunning again and again. We can use a coroutine to set up a spawn manager for our enemies, making them spawn randomly all over our screen and at random intervals too. Let’s take a look at the basic setup for the spawner.

We made a new C# script called “SpawnManager” to handle our spawning system. We attached this script to a new Empty gameobject (also titled Spawn_Manager).

To keep our hierarchy clean, we are going to make another Empty Game Object and call it “Enemy container” which will place as a child of the Spawn Manager. We will be coding our “Enemies” to be created as “children” to our Enemy Container, keeping our hierarchy free of all the enemy objects we will be spawning.

Now lets look at our SpawnManager Script to set up our logic.

The first thing we need to set is a few variables:

This will allow us to attach the enemy prefab we build, as well as the new enemy container to our spawn manager itself.

Drag and drop the appropriate object or prefab into its place on the inspector.

We also need to set a stop spawning variable.

Now the script knows what our enemies are, as well as the enemy container.

Now we can write our coroutine!

This is our actual coroutine’s logic. IEnumerator is the language specific indicator for a coroutine. The coroutine is checking to make sure that _stopspawning is false before continuing the command.

We can then set our positions to spawn variable and use Random.Range to create random enemy placement.

We then instantiate the enemy prefab at postospawn (quaternions influence rotation, which we do not care about here so we can use quaternion.identity to use the default).

After instantiating it, we tell the script that newEnemy is a child to _enemy container.

Finally, we have a yield statement.


Seriously, it will crash your program (and possibly your PC) if you forget to use one. The yield we utilizes tells our coroutine to wait 1 second before rerunning (meaning 1 enemy spawns per seconds).

Now that the Coroutine is written, we need to initiate it. Fortunately, it is extremely simple.

Just type this out in void start.

As we want enemies to spawn as the game starts, we place this command in void Start, so that the enemies start spawning as soon as the player begins the game!

We can use this same logic to spawn in items, enemies, allies, keys, etc, assuming we want them to spawn on a timer.

Next time we will be moving out of the prototyping stage and implementing some basic graphics for our game!

Unity Developer