Waiting with Coroutines

Erin Kerr
3 min readOct 6, 2022
Photo by Kai Pilger on Unsplash

Using coroutines in Unity to implement time delays in processes

What’s a coroutine?

A coroutine is a method that returns an IEnumerator object, allowing you to pause processing of the method and return to it later, picking up from where you left off.

How to write a coroutine

Add a new method to represent your coroutine

To create a coroutine, write a new method in your program that returns an IEnumerator type object.

Add yield statement to wait for one frame

You can enter lines of code like you normally would for a method. Once you reach a place you’d like to pause execution, enter the yield keyword followed by a call to return an IEnumerator. To have the method pause for a single frame, return null.

Add yield statement to wait for five seconds

To specify the number of seconds to pause, return new WaitForSeconds(t) where t is the number of seconds to wait.

How to call a coroutine

While calling most methods only requires that you enter the method name followed by parentheses (ie. MyMethod();). However, to call a coroutine, you actually call another built-in method StartCoroutine() and pass in the name of the coroutine method. There are two options when passing in the coroutine name:

As a string

Call StartCoroutine and pass in coroutine name as a string

First, you can start a coroutine by passing in the name of the coroutine as a string. This is the slower or less performant of the two options, but calling it as a string allows you call StopCoroutine() to manually exit a coroutine.

As a method call

Call StartCoroutine and pass in coroutine name as a method call

Instead, you can start a coroutine by passing in the name of the coroutine as you would normally call a method. This is the faster or more performant of the two options, but, if a coroutine is started this way, it cannot be manually stopped with StopCoroutine().

--

--