Unity and Coroutines

Bob Hilbig
3 min readJul 17, 2021

Code, at its base, is written procedurally and read from top to bottom. In Unity a lot of code is being called during the Update method which is called every frame. But some code only needs to be called once in a while. So we can set flags with timers and if statements inside our update method, or we can create a Coroutine.

Coroutines are great at tasks that only need to be done once a certain condition is met. The conditions can be fairly simple: do this thing every few seconds. Or they can be a bit more complicated: do this thing every few seconds after I press a key but only on Wednesdays unless there is a full moon and then only at the end of a frame.

As our shooter game evolves we need to create enemies to shoot. So lets spawn them in!

Well the spawn function certainly works!

Ok, so spawning an enemy once per frame might be too fast. But the title of this article suggests a feature on Coroutines so lets go with that.

First lets think of some conditions that we require to spawn an enemy. Let’s make sure that the player is alive. And let’s make sure that we don’t spawn them so fast, how about every five seconds. We need a bool to mimic the condition of an alive player.

IEnumerator is .Net but Unity uses it for Coroutines.

Lets examine the above code.
If _stopspawn is false, enter the infinite loop. Elsewhere we can set the _stopspawn bool whenever a condition like the player dying happens.

yield return suspends the code until the yield instruction following it has been completed. In this case, we are waiting 5 seconds before we finish our script. Then we spawn the enemy and go back to the top of the loop and wait another 5 seconds to spawn a new enemy.

If we just left it at this, nothing would happen. We have to start this Coroutine.

We can do this by creating a variable of type IEnumerator. Then we use the StartCoroutine method to start the call.

Best to put this in the Start method so you don’t get stuck spawning enemies galore all over again.

--

--