In Unity, coroutines are a powerful tool that allows you to perform actions over time without blocking the rest of your code execution. Sometimes, you might need to manage your coroutines more flexibly, such as stopping them from outside the method where they were started. To achieve this, you can save your coroutine as a variable.
A coroutine in Unity is started with a call to StartCoroutine, which returns a Coroutine object. This object can be stored in a variable for later use, particularly for stopping the coroutine with StopCoroutine.
Here’s how you can do it:
Step 1: Define a Coroutine Variable
First, declare a variable of type Coroutine at the class level in your MonoBehaviour script. This will allow you to access the coroutine from any method within the class.
Coroutine myCoroutine;
Step 2: Start the Coroutine and Assign it to the Variable
When you start the coroutine using StartCoroutine, assign the returned Coroutine object to your previously declared variable.
void StartSomeProcess()
{
myCoroutine = StartCoroutine(MyCoroutineMethod());
}
Example Coroutine Method
IEnumerator MyCoroutineMethod()
{
// Your coroutine code here
yield return new WaitForSeconds(1); // Just an example of a delay
Debug.Log("Coroutine execution");
}
Step 3: Stop the Coroutine Using the Saved Variable
You can now use the StopCoroutine method with your saved coroutine variable to stop it from executing further.
void StopSomeProcess()
{
if (myCoroutine != null)
{
StopCoroutine(myCoroutine);
}
}
Full Example Script
using System.Collections;
using UnityEngine;
public class CoroutineExample : MonoBehaviour
{
Coroutine myCoroutine;
// Start is called before the first frame update
void Start()
{
StartSomeProcess();
}
void StartSomeProcess()
{
myCoroutine = StartCoroutine(MyCoroutineMethod());
}
IEnumerator MyCoroutineMethod()
{
yield return new WaitForSeconds(1);
Debug.Log("Coroutine execution");
}
void StopSomeProcess()
{
if (myCoroutine != null)
{
StopCoroutine(myCoroutine);
}
}
// Example of stopping the coroutine from another action,
// such as a user input or an event in the game
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
StopSomeProcess();
}
}
}
In this example, the coroutine starts running when the game begins via the Start method. It prints a message after a 1-second delay. If you press the spacebar (KeyCode.Space), it stops the coroutine, preventing further messages from being logged (if stopped within the 1-second delay).
Saving coroutines as variables offers greater control over their execution, allowing you to manage their lifecycle according to your game’s logic.