Coroutines with Unity!

What are they and how do we use them?

Raymond Mills
5 min readAug 28, 2023

What are Coroutines?

In Unity, a coroutine is a method that can be triggered to turn off and then triggered to turn back on, continuing where it left off. Coroutines allow you to execute commands repeatedly under certain conditions, which means you can pause the function and tell it to wait for a condition or action to occur before continuing.

Goal

I am going to use coroutines to consistently instantiate or spawn enemy game objects. I am then going to trigger this function to stop when the player object is destroyed.

Create Spawn Manager

We first need to create an empty game object that will act as our spawn manager. We will name this object appropriately, Spawn_Manager. Then we will create a new C# script. We can name this SpawnManager and attach it to the Spawn_Manager game object. This is how we will control how the Spawn_Manager behaves. Let’s open the script and start writing our code.

Add Enemy Prefab

Our enemy prefab is set to instantiate on game start on the top of the screen at a random coordinate on the x axis. But this is only going to give us one enemy. We can easily instantiate an enemy game object with the Spawn_Manager by creating a variable called _enemy and attaching our enemy prefab to this variable in Unity. We are going to use a coroutine to create a new enemy every five seconds at the top of the screen at a random coordinate on the x axis and stop spawning when the player is destroyed.

Using A Coroutine

We will be using a coroutine type called iEnumerator and name it _SpawnRoutine this will allow us to use the yield command in our spawn manager script. This is essential, so we can tell the method to wait 5 seconds before repeating. We will use WaitForSeconds as our yield type and set it to a value of 5.0f. And set the coroutine to run in the void start method. Everything will look something like this in our SpawnManager script.

Caution: Every iEnumerator method needs at least one yield command or it will not run. With no yield, the spawn manager to instantiate repeatedly, and it would do this all at once creating infinite enemies immediately, causing your computer to crash with no memory to do anything else. So we must add a yield giving the computer time to think between each enemy instantiation.

Stop Spawning

Now we want to make an “on\off switch” so we can tell the game to stop spawning when the player is destroyed. Even though the coroutine runs on game start, we need a way to pause the method if certain conditions are lost and resume, if necessary, once conditions are met again without having to run a new StartCoroutine every time.

First, since the “switch” is triggered by the presence of the player we need the spawn manager to be aware of the players existence. For this, we make a GameObject type variable, name it _player and assign our player prefab to that variable. Then we will create a private boolean type variable, name it _stopSpawning and give it a default value of false.

While Loop

Now we will turn our _SpawnRoutine into a “while loop.”

Caution: These can also be dangerous if not executed properly because your code can get stuck in an infinite while loop and without a way to interrupt this loop your script will never run anything past this point.

So, with that in mind, we will make our while loop with our boolean like this.

While _stopSpawning equals false, which is its default value, then we can run the rest of the _SpawnRoutine method.

We now have a switch that we can deactivate. If _stopSpawning equals true our coroutine will not run again. This is where the _player variable is needed. Using an If statement we will null check the presence of the player GameObject. And if the _player equals null then _stopSpawning will equal true. To do this we to make one more method that we will call _OnPlayerDeath.

The last thing we need to do is make the method _OnPlayerDeath run, and we have successfully ended our while loop.

Since our while loop is running, nothing after it will run until it stops. If we put our “off switch” before the loop, _stopSpawning will not equal false therefore our loop will not run. To solve this problem, we will add our activation code for _OnPlayerDeath to our PlayerBehavior script.

We already have a method for destroying the player when _lives is equal to zero. We will include OnPlayerDeath to trigger at this time as well.

Final Touches

For this to work, we also need to communicate with the _spawnManager script because that is where the OnplayerDeath method exists. And we will set an error message to display if this communication is for some reason not working, by adding a null check to run in the void start of the player script.

The full _spawnManager script looks like this.

Summary

Congratulations, we have successfully created a spawn manager using a coroutine and stopped it from running when the player is destroyed. This may have been a bit tedious, but it works. Just imagine all the possibilities where a coroutine could really innovate your game. My next article will be a short one. I will show you how we can keep our Unity hierarchy window from being flooded with enemy game objects. Don’t miss Containers: Keep It Tidy!

--

--

Raymond Mills
Raymond Mills

Written by Raymond Mills

Unity Software Engineer, I am in an apprenticeship with GameDevHQ. I am taking the steps to become a professional Unity Developer.

No responses yet