Coroutines in Unity

Rusben Guzman
2 min readMay 20, 2021

--

A coroutine is a function that has the ability to stop it’s execution and continue at the same point after a condition is met. To declare a Coroutine you have to use the type IEnumerator:

The IEnumerator allows us to use the following line of code, where yield is a keyword that tells Unity to wait one frame to continue with the execution.

We also can add a time delay using the WaitForSeconds() function as below.

Unity also provides other options like WaitUntil() to wait until a condition is true or WaitWhile() to wait until a condition is false.

The last thing you have to do in order to use your Coroutine is use the method StartCoroutine() and pass your Coroutine as a parameter.

There are a lot of uses for coroutines like a cooldown system for shooting, recharge shields or any mechanic that has to wait for time or conditions in your game.

--

--

Rusben Guzman

A Software Engineer passionate about game dev and interactive products with Unity. I consider video games to be the artistic expression of programming.