A Short Guide: How to Check if a Coroutine is Running in Unity

by Michael Sacco Published May 24, 2023
The cover for A Short Guide: How to Check if a Coroutine is Running in Unity

Introduction

As game developers, whether moonlighting as an indie developer or working in a small game studio, we often rely on Unity’s coroutines to execute code across multiple frames.

When dealing with coroutines, it can be helpful to identify whether a coroutine is currently running. In this article, we’ll take a gander at two different methods to check the status of a coroutine.

Method 1: Use a Boolean Variable

The first approach that we will look at involves creating a class-level boolean variable and using that to track the status of the Unity Coroutine.

In your class, create a new boolean variable named `isCoroutineRunning`.

private bool isCoroutineRunning = false;

Then, go to your Coroutine (the IEnumerator method itself).

At the start of the method, set the value of isCoroutineRunning to true.

isCoroutineRunning = true;

At the end of the method, set the value of isCoroutineRunning to false.

isCoroutineRunning = false;

In this example, we’ve set up the isCoroutineRunning variable, we set it to true when the Coroutine starts, and then we set it to false when the Coroutine ends.

using UnityEngine;
using System.Collections;

public class CoroutineExampleBoolCheck : MonoBehaviour
{
  private bool isCoroutineRunning;
  
  void Start()
  {
    StartCoroutine(ExampleCoroutine());
  }
  
  IEnumerator ExampleCoroutine()
  {
    isCoroutineRunning = true;
    Debug.Log("Coroutine started");
    
    yield return new WaitForSeconds(2f);
    Debug.Log("Coroutine resumed after 2 seconds");
    
    yield return new WaitForSeconds(1f);
    Debug.Log("Coroutine will end after another second");
    
    yield return new WaitForSeconds(1f);
    isCoroutineRunning = false;
    
    Debug.Log("Coroutine ended");
  }

  void Update()
  {
    if (Input.GetKeyDown(KeyCode.Space))
    {
      if (isCoroutineRunning)
      {
        Debug.Log("Coroutine is running");
      }
      else
      {
        Debug.Log("Coroutine is not running");
      }
    }
  }
}

You can check the value of this variable at any time. The result will tell you whether the Coroutine is running.

This approach is nice because it sets up an explicit variable to monitor the status of the Coroutine. It also makes it easy for us to do straightforward status checks on the value of this variable.

Method 2: Examine the Coroutine Object

The second approach that we will cover involves creating a Coroutine object, assigning the new Coroutine to that object, and then interrogating the object about the state of the Coroutine.

First, you will create a new Coroutine variable.

private Coroutine coroutine;

Then, use StartCoroutine() to start your coroutine. StartCoroutine returns the new Coroutine object, so assign it to your Coroutine object.

exampleCoroutine = StartCoroutine(ExampleCoroutine());

This Coroutine object is null if it has not yet been assigned. When it starts running, we assign the result of StartCoroutine to it. Then, when the Coroutine finishes, we will set the value of the Coroutine object to null.

exampleCoroutine = null;

By storing the reference to the coroutine in a variable, we can check if the variable is null to determine if the Unity coroutine has finished executing.

You can easily set a local variable, like isCoroutineRunning, based on the status of the Coroutine object. In this case, we’ll check if the Coroutine is null property to determine whether the coroutine is running.

bool isCoroutineRunning = exampleCoroutine != null;

using UnityEngine;
using System.Collections;
public class CoroutineExampleNullCheck: MonoBehaviour
{
    private Coroutine exampleCoroutine;
    void Start()
    {
        exampleCoroutine = StartCoroutine(ExampleCoroutine());
    }
    IEnumerator ExampleCoroutine()
    {
        Debug.Log("Coroutine started");
        yield
        return new WaitForSeconds(2 f);
        Debug.Log("Coroutine resumed after 2 seconds");
        yield
        return new WaitForSeconds(1 f);
        Debug.Log("Coroutine will end after another second");
        yield
        return new WaitForSeconds(1 f);
        exampleCoroutine = null;
        Debug.Log("Coroutine ended");
    }
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (exampleCoroutine != null)
            {
                Debug.Log("Coroutine is running");
            }
            else
            {
                Debug.Log("Coroutine is not running");
            }
        }
    }
}

This method provides a direct way to access the status of the coroutine and enables us to make direct checks to that Coroutine object based on its execution state.

Choosing the Right Method

As game developers, it is good to know your options when thinking about how to check the status of a coroutine.

When thinking about which option to implement for your project, make sure that you consider factors such as simplicity, code organization, and any additional functional requirements as well.

These two options provide us with clear and intuitive ways to determine if a coroutine is running, which can make it easier to develop a Unity project without getting stuck on maintaining Coroutine state.

Conclusion

For indie game developers and those working in small game studios, the ability to check the status of a Unity coroutine can be important in order to maintain control over code execution.

If you know whether a coroutine is running, you can prevent conflicts, enable conditional logic, and provide user feedback more easily.

By using the two options that I touched on in this article, you can easily check if a coroutine is running in order to more easily develop the target functionality for your Unity project.

Thanks for reading!

Free download: Indie Game Marketing Checklist

Download now

Category

resources

Don't forget to share this post!

Popular assets for Unity

See all assets ->
    Cutting-edge volumetric fog and volumetric lighting with support for transparent materials.
    Volumetric clouds, day night cycles, dynamic skies, global lighting, weather effects, and planets and moons.
    A lightweight procedural skybox ideal for semi-stylized projects.
    Image-based Outlines for 2D and 3D games with variable line weight, color, and displacement options.
    Drag-and-drop ready-to-use ambient, impact, and spell particle effects.
    Per-pixel gaussian blur on your entire screen, part of the UI, or in-scene objects.

Free Indie Game Marketing Checklist

Learn how to make your game successful with this handy checklist.

Download for free