Nerd For Tech
Published in

Nerd For Tech

Coroutines in Unity

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!




NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit

Recommended from Medium

How to validate a TAR file in C# .Net Framework

Automate follow & unfollow users on twitter with this unofficial Twitter Api

NMI Watchdog on Linux

How to convert Photoshop PSD to JPG in Node.JS

Codeblocks Fundamentals: Using the Create Group Codeblock for Addition (Union), Subtraction, and…

Write code in the natural English language with AI generated code

Raspberry Pi Setup Tutorial

Safely Draining a K8s Node

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ryan Sweigart

Ryan Sweigart

An independent Unity Developer.

More from Medium

My journey becoming a Unity game developer: 2.5D Infinite Runner-Ledge Grab System-Pt4

How to Install the Universal Render Pipeline

Creating objects in Unity

Benefits of Prototyping with Cubes