Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Garbage collection when Scene unloads

Discussion in 'Scripting' started by eco_bach, Apr 11, 2021.

  1. eco_bach

    eco_bach

    Joined:
    Jul 8, 2013
    Posts:
    1,601
    What are some good practices when unloading a Scene in terms of garbage collection?
    Should this code be put in an OnDestroy method or?

    I am using no EventDispatchers but I am creating a new gameObject based Dictionary every time my Scene loads. (called from Start())

    The actual dictionary is initialized in a private var as
    Code (CSharp):
    1. private Dictionary<string, GameObject> meshObjects = new Dictionary<string, GameObject>();
    Should I instead be initializing it in my Awake or Start methods? And then setting to null OnDestroy?
     
    Last edited: Apr 11, 2021
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    I wouldn't sweat that tiny object.

    Make sure nothing that is marked DontDestroyOnLoad() maintains links to things that get unloaded.

    I suppose you could. I never bother unless it is a static quantity, which obviously lives forever unless you do null it out.
     
  3. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,894
    There's no need to nullify your variables inside OnDestroy. The garbage collector will sort it all out.
     
    Kurt-Dekker likes this.
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    This is almost universally true. With most typical Unity usage patterns, load your next scene and just move on. It's rare that you have to agonize about "best practices" for scene loading and unloading. Just get on with things.