What happens to pointers to a GameObject when it is destroyed?

When using Destroy(GameObject) it is supposed to destroy GameObject from the scene. If however I have a variable pointing to this GameObject, it is not null after I have destroyed it. Does that mean it still lingers in memory? How are the details around this?

How long after Destroy() is it still retaining a reference? If it’s more than that 1 Frame/Update() it might be a bug.

Actual object destruction is always delayed until after the current Update loop, but will always be done before rendering.

If you don’t want to wait for the Garbage Collector, you could use DestroyImmediate. Advise against it tho.

I was doing this:

Destroy(object);
if (object == null) {
  print("object = null");
} else {
  print("object != null");
}

and it gave “object != null”. Then I did the same in Update, and noticed that one frame later it was set to null. So thanks, I guess the garbage collecter just doesn’t work imidiately.

In your example, it’s pretty clear that the Update loop would not have been completed before you check is done.

As an important note, even after calling Destroy() and waiting a frame, the Garbage Collector has not cleaned it up.

In fact so long as you don’t explicitly set that reference to null the object will not be cleaned up.

object == null is because of an override between GameObject/MonoBehaviour on the == operator. It’s not really null, it’s just no longer usable. When destroying gameObjects, if you want to get them to be explicitly cleared from memory (on the next cleanup), you have to set all references to point to either something else, or null(even if it already equals null).

The garbage collector doesn’t touch Unity objects like GameObjects at all. For that you need Resources.UnloadUnusedAssets (was known as Application.GarbageCollectUnusedAssets in Unity iPhone). This is called automatically before loading a new level, assuming that UnloadUnusedAssets has the same behavior as GarbageCollectUnusedAssets.

–Eric