Coroutines with Unity!

Bill Rislov
3 min readApr 10, 2021

--

A coroutine is used to pause execution and return control back to unity but will continue where it left off on the next frame. unlike a normal function where it will run to completion before returning, this means that everything in the function must take place within a single frame.

A coroutine is declared with a type of IEnumerator and uses the yield return statement. The yield return is when the execution pauses and resumes the following frame. We can also use the WaitForSeconds to pause for a certain amount of time.

To call a coroutine you will use the StartCoroutine() function.

Enemy Spawn Routine

There are many elements of a game where you may want to have a pause in the execution, The one I will be exploring is spawning enemies in my 2D Space Shooter game.

Objective:

Spawn an enemy every 5 seconds at the top of the screen and randomly on the x-axis between -8 and 8

Method:

First, we will need to define the position to spawn the enemies. we will use Random. Range to define the x-axis and a set value for the y-axis. To find these values, I will drag the enemy in the scene view and note the values of the x-axis and the y-axis.

Finding spawn values

I have determined the y-axis will be 7.0f and the x-axis will be between -11.3f and 11.3f

Position to spawn enemy

Then, we will need a variable to allow us to stop the spawning when the player dies, this will be a bool variable.

bool variable

This will be set to true in a method I called OnPlayerDeath. This will be called from the player script when the player lives are zero. To find out more, check out my article on script communication

on player death method
calling method from the player

Now that we have the position to spawn and a way to stop the spawning, we can put together the coroutine function. I will use the WaitForSeconds to delay the spawning for 5 seconds

Enemy Spawn Routine

The Enemy Spawn Routine in Action:

Enemies Spawning

Happy Coding!!

--

--