Can I check if this.gameObject was destroyed?

Here’s a simple version of a coroutine that’s running on one of my objects:

public IEnumerator PulseOnGround()
    {
        while (gameObject.activeInHierarchy)
        {
             //do stuff
             yield return new WaitForFixedUpdate();
             if (gameObject == null) yield break;
        }
    }

This throws a MissingReferenceException when the object is destroyed from another script. It appears that the script keeps running after it’s destroyed, but I can’t find a way to check if the gameObject still exists from within the script.

Is it possible to break this coroutine on destroy from within this script, without using StopCoroutine? Or do I need another script to keep track of whether this script is still alive and call StopCoroutine on any coroutines that might still be running?

I’m trying to do this without StopCoroutine because I don’t have references to every coroutine that’s running, and I would want all of them to stop on destroy anyway.

I added a helper extension for this:

using System;
using UnityEngine;

public static class Helpers {
    public static bool IsValid(this MonoBehaviour comp) {
        try {
            if (comp.gameObject == null) return false;
        } catch(Exception) {
            return false;
        }
        return true;
    }
}

Now in my MonoBehaviours I can just check that and abort:

if (!this.IsValid()) return;

Hi, may be you need to check it by a different way, when you use a component to check if his game object is still alive, this always drops a Null Reference Exception because the method still works on memory until finished his job, that’s why you get that warning; the better way doing this is if the tracker of that object check it, not the object it self.

This might be a little old, but have you tried changing your loop to:

 public IEnumerator PulseOnGround()
     {
         while (gameObject != null && gameObject.activeInHierarchy)
         {
              //do stuff
              yield return new WaitForFixedUpdate();
         }
     }

In this way you avoid the exception from gameObject.activeInHierarchy

On most of my games in which the player could die I don’t destroy the gameobject, but I just Deactivate it by using: gameObject.SetActive(false);. You could also create a GameObject variable of an object that the script component isn’t on, assign it, and do NameOfObject.SetActive(false);. You could put NameOfObject.gameObject.SetActive(false); if it doesen’t work but it likely will.

When the GO is destroyed the updates on it’s child MonoBehaviours might still run for a frame.

I find adding a check at the top of the MonoBehaviour’s Update method such as

 if (this == null) return; 

is sufficient.