Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice

Memory leak dependent on how you destroy an object

Discussion in 'Profiler Previews' started by roberto_sc, May 5, 2020.

  1. roberto_sc

    roberto_sc

    Joined:
    Dec 13, 2010
    Posts:
    144
    If you have a reference to a MonoBehaviour and you call Destroy or DestroyImmediate on it or on its game object it will leak an empty shell .NET object.

    The same doesn't happen if you manually delete the game object via editor hierarchy. In this case the .NET object is deleted and GCed. Why does this happen?

    This is important because it shows that there's a way to completely remove an object from memory, it feels like I'm doing something wrong in the code.
     
  2. alexeyzakharov

    alexeyzakharov

    Joined:
    Jul 2, 2014
    Posts:
    507
    Do you set the reference to null? More likely it is that there is something referencing MonoBehaviour and preventing GC from picking up the shell. In complex cases Memory Profiler usually helps to determine the class/object which holds the reference.
     
  3. roberto_sc

    roberto_sc

    Joined:
    Dec 13, 2010
    Posts:
    144
    I don't set the reference to null, that's the point: I'm aware that having a reference to it will prevent the object to be collected, my question is why manually deleting the game object in the editor will make the object to be GCed, why is there a different behavior?

    I see why my post is misleading, I asked for "a way to completely remove an object from memory" and you correctly answered that I should set the references to null; so please let me detail my problem further: I'm in a fairly big project with thousands of objects being leaked (destroyed game objects components that should be GCed). We are doing a huge amount of work to properly fix these leakings, but when I saw that destroying the GO manually would free the empty shell object it got me thinking if there's a way to free all this memory without having to fix the code.