Coroutines with Unity!

Richard Morgan
May 16, 2021

--

As an alternative to the Update method, there is another way to create code loops in tandem with the Update method. This is useful when code needs to execute independent of the frame-by-frame procedural execution of the Update method without delaying any other processes.

To call a coroutine in Unity we use StartCoroutine(). A coroutine returns a value of type IEnumerator. In this example, we’ve created our IEnumerator coroutine to spawn a new enemy every second:

This while loop will never complete so this coroutine will never end, but at the same time does not prevent us from executing other methods simultaneously from the Update method.

Using coroutines in Unity gives us more control over the lifecycle of the execution of a method.

--

--

Richard Morgan

Unity and Flutter developer interested in creating mixed-reality applications.