Unity Fundamentals — Coroutines

Jose Gil
2 min readApr 12, 2021

--

So you want more control or customisation of your events occurring in every frame provided by the Update function. If this is the case, let me introduce you to Coroutines.

A Coroutine is like a function that can pause execution and return control to Unity until a condition or action takes place for it to continue. Consider it to be a routine that you want to carry out.

In Unity, we specify a Coroutine as a IEnumerator.

IEnumerator CoroutineName()
{
// Your Code
}

By default, a Coroutine is resumed on the frame after it yields, but it is possible to introduce a time delay using a Yield command. Accompanied by a WaitForSeconds, the yield command can pause the Coroutine for however long you specify.

IEnumerator CoroutineName()
{
Actions to be performed;
yield return new WaitForSeconds(5.0f); // 5 seconds
}

Lets, take a real example. We want to spawn an enemy every five seconds in a random X location between -2.3f and 2.3f.

In the above example of a SpawnManager; We use an infinite loop to create the enemy every 5 seconds within the IEnumerator and Yield. You will notice that we started the IEnumerator within the Start function.

Danger — Infinite loops should be used with caution as if not appropriately controlled; they can crash your game or computer.

I hope this article has helped you with Coroutines and IEnumerators. Check out my other articles on Unity Fundamentals.

--

--

Jose Gil
Jose Gil

Written by Jose Gil

Unity Developer at Mooski Games

No responses yet