Coroutines in Unity

Matthew Clark
3 min readMar 27, 2021

What is a Coroutine?

Coroutines are a method that allows you to suspend or delay a function until an action or condition is fulfilled. They allow you to split functions up and have them run in the order you want. This is useful when you want to have an action take place over a set amount of time.

The power up uses a coroutine to determine how long it is active.

How to Use Coroutines?

A coroutine is created in a similar way to normal functions. A normal function will use type void but a coroutine will use an IEnumerator. An IEnumerator is a type of function that requires a return value. This value is what determines how long your function will be delayed.

To start a coroutine you reference the function using StartCoroutine.

The Different Types of Yield Return

Null

  • yield return null will wait for the next frame before it continues

Wait For Seconds / Wait For Seconds Real Time

  • wait for seconds will take an exact amount of time and continue after that time has passed
  • wait for seconds real time works the same way but is not affected by things like pausing the game

Wait Until / Wait While

  • yield return wait until delays until a delegate value is true
  • yield return wait while delays until the value of the delegate is false and then it will execute

Wait For End of Frame

  • wait for end of frame waits until unity has rendered every camera and GUI, right before the frame is displayed on screen
This is a good way to capture screen shots

Wait For Another Coroutine

  • yield return StartCoroutine(Coroutine()) will wait for another coroutine to finish before it executes

--

--