Coroutines with Unity

Jason Schneider
2 min readJul 6, 2021

What is a Coroutine?

A Coroutine is a method in Unity, which allows us to execute game logic over a number of frames. What this means is that we can pause a function and tell it to wait for a condition or action to occur before continuing. Therefore we can split up its functionality into a number of steps that can be executed in order.

When should I use a Coroutine?

It’s worth considering using a Coroutine whenever we want to create an action that needs to pause, perform a series of steps in sequence or if we want to run a task that we know will take longer than a single frame.

How do I write a Coroutine?

In Unity, we call a Coroutine by using the IEnumerator method.

Visual Studio shows us that there will currently be a compiling error with the squiggly line. This is because all IEnumerator methods need to encompass a yield statement.

However, if we attach this script to a game object it is not going to do anything, as we have not set up anything for it to do.

The above code will print to the console every 2 seconds for as long as the program runs, after we start the Coroutine using the below code.

Continually printing every 2 seconds.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response