MissingReferenceException

Hi,

I have an arraylist of objects - they’re all instances of monobehaviour-based classes, that all implement an interface. Every now and then, I need to loop through this array, and do something with these objects. The problem is, sometimes one of the gameobjects corresponding to these objects has been destroyed, so I’m getting an error that tells me the object of type X has been destroyed, and to either check if the object is null, or not to destroy it.

The problem is, if I check if the object is null, I get false. I can Debug.Log the object and still get the name of the class it belongs to.

But if I check if object.gameObject == null, I get the same error telling me that the object of type X has been destroyed.

To clarify (untested pseudo-code) :

for(int i=0;i<objects.Count;i++) {
	if(objects[i]!=null) {
	// this returns true

		if(((MonoBehaviour)objects[i]).gameObject!=null) {
		// this throws a MissingReferenceException

			// do stuff
		}
	}
}

Any ideas on how to solve this? It is not an option to remove the object from the arraylist manually when it gets destroyed.

Thanks!

how about a try/catch statement that deals with the exception?

Already tried that. Worked in the editor, not on the device - probably because I have my project set to “Fast but no exceptions”, but I’m not sure.

Anyway, I did find a way to remove the items from the arraylists when they are destroyed, without hurting performance (much). So I’m no longer stuck. However, I would still like to know how I’m supposed to check if a gamobject has been destroyed.

I understand that the way this is implemented internally is that a small wrapper for a scene object is preserved even after the object itself is destroyed. Try casting the object to MonoBehaviour in the outer null test - I think that should trigger some internal magic stuff that returns the correct null reference.