Co(ol) your jets and get out of a routine

Zach Lo
2 min readMay 5, 2021
Photo by Phil Hearing on Unsplash

Coroutines allow us to yield or suspend our application by telling our program to wait a set amount of time before continuing on it’s merry processing way. To use coroutines we use a special type called IEnumerator which is a type of collection of “enumerated types” or a return type from another perspective.

From a Unity point of view it allows us to use the “yield return new” keywords.

How do we use it? Let’s take a look at a simple example. Say you want to execute a command, but would like to wait a certain amount of seconds between commands using a coroutine lends itself nicely for this type of application.

We start by using type IEnumerator and naming the method, within the method we want to print out how many seconds has passed then move onto the next print statement. To do this we use the “yield return new” keyword and append a method “WaitForSeconds()”, and we pass in the amount of time in seconds we want to wait before we print out. Then we repeat the process for any additional incremental time we want to have pass.

Great, now we run our application, but nothing happens. The key is we haven’t told our coroutine to run. How do we begin? In our start method we need to type the method “StartCoroutine()” and pass in the method of our type IEnumerator. Now when we run our application we see that our message gets printed out and after two seconds the next message is printed and so on.

--

--

Zach Lo

Unity Developer | Community Manager with a passion for tech and entertainment