Coroutines in Unity

Ryan Sweigart
Nerd For Tech
Published in
2 min readSep 17, 2021

--

Objective: Change object’s color randomly every every two seconds.

A coroutine will allow us to execute a process while other processes are being run. Coroutines are also useful when we want to delay a process. In our example, we’ll do both: Change color while the shapes are spinning, waiting 2 seconds between each change.

We’ll begin by setting our wait time (2 seconds) and caching references for the object’s MeshRenderer and a WaitForSeconds class.

In the Start method, we’ll get the MeshRenderer component of our object and define the WaitForSeconds class. Then we’ll call the ChangeColorRoutine coroutine (More on that in a bit).

Even though we’ve called the coroutine, our Update method will continue to run, causing our object to rotate.

While Update is rotating our object, the ChangeColorRoutine coroutine will wait two seconds, then assign a random color to our MeshRenderer. Since our while statement is always true, the script will continuously wait 2 seconds then change the color!

--

--