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.
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.
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.