What is the proper way to stop a coroutine if the GameObject is not active?

Hi all, I wonder what method do you use to terminate a coroutine? Like I a script attached to a gameObject, running a coroutine and yield to wait for execution. And suddenly in the runtime, the player triggered something and deactivated this gameObject. Then how should I stop the coroutine? Or pause the coroutine? I think checking that in Update() function (activeInHierachy) isn’t the best way.

Any idea? I bet most of you encountered this problem. Thanks in advance.

What I usually do is set up a public flag

class Example : MonoBehaviour
{
	public bool alive = false;
	
	public IEnumerator MyCoroutine()
	{
		alive = true;
		// do your initialization here
		while (alive)
		{
			// do your loopy thing here
			yield return null;
		}
		// do your cleanup here
		alive = false;
	}
}

Then set up “alive” to false when I want the coroutine to stop. If you want it to happen immediately after the object gets deactivated, simply add.

void OnDisable()
{
	alive = false;
}

to your Monobehaviour class