Coroutines with Unity

Christian Carter
2 min readMay 18, 2021

A normal function called through either the Start or Update functions will have the entire function completed in one frame. Coroutines are useful for having a function execute across multiple frames. This is useful in multiple situations like fading an object out of existence or spawning enemies.

To create a coroutine function instead of having the return variable be void you will set it to IEnumerator. That will allow the function to be called as a coroutine. This type of function requires as special return called a yield return. What is returned from the yield return affects how many frames it waits before running the next portion of the function. If it returns null then to code after the yield return will execute in the next frame. If it return a new WaitForSeconds() function it will wait the number of seconds that you pass to WaitForSeconds and then the code after it will execute in a frame at that time. Below you can see the code version of this example.

IEnumerator Example() 
{
//Executes in current frame
yield return null; //Executes in next frame yield return new WaitForSeconds(5.0f); //Executes in the frame 5 seconds from now
}

To have the coroutine do something over multiple frames it is best to use a loop. If you have a specific number of frames you want something to happen over it is best to use a for loop. If you want it to run forever or until a specific event happens you can use a while loop. Using a while loop that runs forever can be done by setting the value to true like while(true) this will run forever. This is also very dangerous. If it is always running it could overload your computer or crash your game. To prevent this in a coroutine you can use yield return new WaitForSeconds. That will allow your computer space to run. Below is an example of a while true implementation.

IEnumerator Example() 
{
while (true)
{
// Executes every 5 seconds
yield return new WaitForSeconds(5.0f);
}
}

The last thing to do to get the coroutine running is to call it. That is done in the start function by using the StartCoroutine function. You can pass it the coroutine function either as a string, StartCoroutine("Example"), or just by calling the function, StartCoroutine(Example()). Each method has some differences which I will not go into here, but both will work for our example.

If you want to learn more about coroutines you can check the documentation here.

Good Luck Adventurer!

-Chris

--

--