UnityEngine.Object Garbage Collection.

When I call Object.Destroy on a UnityEngine.Object instance it eventually gets destroyed and evaluates to null. The rest of this post here is assumption.

Afaik this is not a standard thing for C#/.net with garbage collecting so I assume whats actually going on is UnityEngine.Object overrides the equals operator so that once its marked as destroyed it evaluates to null.

If this is how unity does it, Does that mean that any reference to the object still existing after its been destroyed is still holding some data from being collected?

Its very easy to hold a reference of something, For example if you use events and event handlers or have a list.

For this reason for things like events i always use the OnDestroy function to remove a event handler inside the component or scriptable object from any events its been added to.

Basically it’d be good to know how its actually working under the scenes because if i didnt have to do things like above i wouldnt. If its actually setting all things that reference it to null somehow, or if the equality operator override is actually making the garbage collector collect that would be great, but again it’d be good to have some reassurance it is.

No Unity objects are garbage-collected, if that’s what you’re asking. Only Mono objects are handled by the garbage collector. You can use Resources.UnloadUnusedAssets for Unity objects.

–Eric

Thanks for the response, So to be clear if i have something like:

static class SomeSingletonSystem{
    public delegate void FunctionDelegate( );
    public event FunctionDelegate onAct;

    public static void Act() { if( onAct != null ) { onAct(); } }
}

class SomeComponent : MonoBehaviour { 
    void Awake() { SomeSingletonSystem.onAct += this.DoAction; }
    void DoAction() { Debug.Log(name + " did action "); }
    void OnDestroy() { SomeSingletonSystem.onAct -= this.DoAction; }
}

is that OnDestroy function unnecessary? and without the OnDestroy function what happens if a gameObject with the SomeComponent component gets destroyed and then SomeSingletonSystem.Act() gets called?

Or i should ask will destroying the component automatically remove the this.DoAction from SomeSingletonSystem.onAct?