Unity Coding — Coroutines

Christopher Graf
2 min readMay 15, 2021

If you have been following the Unity Developer Journey with me, we have talked a lot about reading and using time in our code. We’ve used Time.deltaTime in our Update() function. We’ve used Time.time for a cooldown. Now we are going to wait for some time with coroutines.

Coroutines are functions that allow you to wait for any amount of time before, after, or in between your regular tasks. This can be extremely useful when with your game design. Maybe after getting hit you want the player to be immune for a few seconds, then return to normal. With a coroutine, that is no problem.

When using a coroutine, there are a few specific things to remember. First, when calling an coroutine, you cannot simply write the name of the function ending with ‘()’ like you normally could. You have to say StartCoroutine() and place the name of the coroutine in the parenthesis.

Next, to specify a function as a coroutine, it must start with IEnumerator.

With the function being specified as a coroutine you also have to actually use its specific abilities. So make sure to add a ‘yield return new WaitForSeconds()’ and then a specified amount of time in the parenthesis. You could also add a ‘yield return null’, which will simply wait for a single frame.

Without at least one of those you will get an error.

Beyond that, it is up to your design and imagination on how to use these powerful devices. Experiment and see just what you can come up with.

--

--