Search Unity

Feedback Disposing!

Discussion in 'Scripting' started by andyz, Sep 6, 2019.

  1. andyz

    andyz

    Joined:
    Jan 5, 2010
    Posts:
    2,276
    Some unity classes are IDisposable (WWW was), most (?) UnityEngine Objects require Dispose - erm Destroy - to be called or a Resources.UnloadUnusedAssets - textures, meshes etc.

    The need for destroy & dispose calls just does not seem well documented, I sense it isn't just me that took ages to learn about this?! Or did I miss something?

    Anyway I was wondering if warnings could be enabled for missing Dispose calls in some way, C# is so robust to use in many ways but disposable objects (including Unity's 'special' native objects) is one place you maybe can fall down and lose track of memory.
    Or does detailed profiling cover this?
     
    Last edited: Sep 7, 2019
  2. Dameon_

    Dameon_

    Joined:
    Apr 11, 2014
    Posts:
    542
    The problem here is garbage collection. You don't necessarily want to do Resources.UnloadUnusedAssets every single time something gets destroyed, and you rarely want to even just destroy objects during gameplay. That kind of stuff generates a lot of garbage, and is the sort of thing you'd do when switching scenes. The Dispose pattern is normally done when we're using native/unmanaged resources that have to be manually disposed of when the object is no longer referenced.

    UnityEngine.Objects require Destroy (which isn't exactly the same as dispose) because they are essentially C++ objects with a C# interface with non-managed memory that needs to be cleared correctly to prevent memory leaks.
     
    Last edited: Sep 6, 2019