How to Use Coroutines

Matthew Givens
2 min readMay 3, 2021

In Unity coroutines solve an important problem. Normally, functions run to completion before returning. If we wanted to create a procedural event, such as spawning enemies based on time, the function would execute in one frame update and finish. Instead we can use a coroutine to build this sequenced event because they have the ability to pause execution and continue based on time or frame information. We will get into how to write them next, but Unity requires “StartCoroutine” to begin execution.

Coroutines use the return type IEnumerator and require a yield statement in the body. After starting the coroutine, Unity will run it until a yield is hit. In “yield return null” it will continue next frame. For our use we want to instantiate enemies on a time delay, so we will use the class “WaitForSeconds” and a data type of float to represent time until continuing to run. In our example we use an infinite loop, so it is essential to use a yield return or write conditional logic that will eventually be false.

--

--

Matthew Givens

A self-taught Unity developer, learning more everyday and documenting my journey. My passion for the world of game development grows with every skill I pick up.