A Short Guide: How to Check if a Coroutine is Running in Unity
.avif?height=300)
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.
Create a free account, or log in.
Gain access to free articles, game development tools, and game assets.