Day 12 | Coroutines in unity

Ted Lim
2 min readApr 6, 2021

Have you been struggling with setting events to occur at scheduled times? Maybe you’ve been working on spawning enemies to appear at a certain rate. This article will go over how to delay/set up events to occur at specific times using Unity Coroutines.

What are Coroutines?

In Unity, a Coroutine is a function that can pause and resume its task in mid-execution. This is unique as functions normally must run to completion before returning control to Unity so that it can continue executing the remaining code.

Example Use Case

One example where a Coroutine is useful is when a game has a series of obstacles a player must dodge to survive. Say I want the player to be able to run through all the falling objects. I’ll spawn the objects in a line and try to run the player through the obstacles.

Well, this isn’t very exciting. Right now, there’s no way for the player to clear the obstacle. If I simply speed my player up, then it’s as if the obstacle isn’t there. So how can I make this more exciting?

Implementing the Coroutine

With a Coroutine, I can delay each obstacle from falling so that the player can clear the obstacle while making it look perilous.

StartCoroutine(IEnumerator routine);

In code, you’ll start a Coroutine by using StartCoroutine() to call an IEnumerator method. The IEnumerator can be paused in the middle of its execution using the keywords, yield return. Most commonly, yield return is paired with a Wait function to execute the pause for a specified amount of time.

Applying this to our game, we want to stagger the spawning of the obstacles so that players must time their movement precisely to clear them. In pseudocode, we can do the following:

//Example Coroutine Structure
StartCoroutine(StaggerObstacles());
IEnumerator StaggerObstacles()
{
//Spawn a ball at the current position
//Wait for a second
yield return new WaitForSeconds(1.0f);
//move the spawn position to the right
}

Result

After implementing the code and adding it to the obstacle spawner, we get the following result:

Hopefully, this explanation made Coroutines feel more approachable. The Coroutine concept is something that you will explore further in Unity as you make more complex games. Good luck!

--

--