Using Coroutines In Unity!

Vincent Taylor
2 min readJun 28, 2021

Functions in Unity are designed to run and return all in one frame. You can’t delay parts of the function or have it go on for multiple frames.

Sets alpha to 0 in 1 frame, despite being in a repeating loop

Like normal functions, coroutines are written in the syntax of: an optional access modifier, the return type, and the function name. The return type must be IEnumerator though.

Any coroutine must also include at least one yield return, if it is meant to span over multiple frames.

Types of yield returns

Using these, you can tell the program to wait until the next frame, wait until the next FixedUpdate function, wait for a specific number of seconds (real-time or game-time), wait until a condition is true, or wait while a condition is true.

To make the earlier example a functional coroutine:

Since coroutines are an ongoing process, they must be started using the StartCoroutine function, not called like normal, from any function.

2 ways to start the coroutine

--

--

Vincent Taylor

Unity game developer / C# Programmer / Gamer. Australian (Tasmanian) indie games developer for 10+ years. Currently looking for games industry employment.