Hurry Up and Wait with Coroutines

While it’s great that you can use Update() to make something happen every frame, have you ever wanted to just slow things down a little? Unity’s Coroutines allow you to do just that!

What’s a coroutine?

A coroutine is a type of method that allows you to pause processing at a particular line of code. Normally, the computer will process an entire block of code in order from top to bottom before moving onto the next section. With a coroutine, you can pause at a particular instruction and pick up where you left off after a specified amount of time.

How to write a coroutine?

There a few different components that make a coroutine different than other methods:

  • IEnumerator return type
  • Yield keyword
  • StartCoroutine call

IEnumerator return type

Methods like Update() and Start() are generally preceded by the word void to indicate that the method does not return a value. However, if you were building an addition method for a calculator program, you would likely use the return type float, so that you could return the value of the calculation. By returning the calculated value, you can assign the output of the method to a variable.

Example of Addition method for a calculator

In coroutines, you use the IEnumerator return type which enables you to use the yield keyword in your return statement.

Example of IEnumerator return type

Yield keyword

In coroutines, the yield keyword allows you to suspend processing on the current method at least until the next frame, if not longer. Once the specified time or number of frames has passed, the method will resume processing where it left off.

Example using yield return null

In the example above, the method will print “Bond”, wait until the next frame, and then print out “James Bond”. For a more dramatic effect, we can use WaitForSeconds() to specify an amount of time to wait before resuming the method.

Example using yield return new WaitForSeconds()

In this example, the method will pause two seconds in between printing “Bond” and “James Bond”.

StartCoroutine call

Once you create a coroutine with an IEnumerator return type and the yield keyword, you’ll have to call it, similar to other methods. Unlike other methods, however, you cannot call a coroutine directly.

A coroutine cannot be called directly — this code will not function correctly

To call a coroutine, you have pass it in as a parameter to the StartCoroutine() method. You can identify the coroutine using a string that matches the name of the coroutine or by passing in the method call directly.

Examples of calling StartCoroutine()

Why use coroutines?

There are multiples uses for coroutines to achieve a sort of parallel processing in your project. In addition to pausing between two lines in code, as discussed above, coroutines allow you to repeat actions or tasks over time as well. If you wanted to implement a random of stream of enemies to continue spawning while the game is running, you could use a coroutine to accomplish that. Let’s take a look.

Objective: Spawn enemies at a random location above the screen every five seconds while the game is running.

First, you’ll need to get a reference to the enemy prefab to use for instantiation, which you can assign in the Inspector.

Get a reference to the Enemy prefab

Next, you’ll need to design a coroutine that can repeatedly spawn enemies for the length of the game, which you can use a while loop to accomplish. A while(true), also called an infinite loop, will always repeat as true can never be false.

Use an infinite while loop (while(true)) to repeatedly spawn enemies

Within the while loop, you’ll need to instruct the program to pause this method for 5 seconds, using yield return and WaitForSeconds().

Use yield return new WaitForSeconds() to pause for the desired amount of time

Then, we’ll need to generate a random X value within the screen limitations and create a new Vector3, so we can set the position of the new enemy during Instantiation.

Generate a random X value to create a Vector3 and instantiate the Enemy prefab

Finally, you’ll need to start the coroutine using the StartCoroutine() method.

Use StartCoroutine to start the coroutine

Then, you’ll have a stream of enemies constantly generating over the length of the game.




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Introduction to NumPy

CS 373 Spring 2021: Kevin Chen

Before you Build: What You Need to Know to Launch a BigCommerce Marketplace Theme

Azure AD Basics

Structures in Python

Congrats to the Winners of the NGINX for Good Hackathon

DevOps automation

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
Erin Brown

Erin Brown

More from Medium

Indy Pro ’22: IWTV

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

Pixel 6/Android 12, a couple of months in

P6: Creating a Gritty Office Den