Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved Question About DontDestroyOnLoad

Discussion in 'Scripting' started by minhson0808, Oct 9, 2023.

  1. minhson0808

    minhson0808

    Joined:
    Oct 9, 2023
    Posts:
    1
    I declared DontDestroyOnLoad on a GameObject that hold my Menu script. However in that script, it creates and reference both monobehaviors and standard type script. When the scene changes, do the references inside the menu script get destroyed?
     
  2. Nad_B

    Nad_B

    Joined:
    Aug 1, 2021
    Posts:
    326
    Yes if the referenced MonoBehaviors belong to other game objects (and are not children of the object).
     
    minhson0808 likes this.
  3. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    4,019
    Careful: the referenced components may be destroyed when you change the scene, but the references themselves will NOT be set to null automatically! This can lead to "MissingReferenceException" or "ObjectDisposedException" types when you try to access these references. It still remains your job to set those references to null or other (valid) references when changing scenes.
     
    Nad_B and CodeRonnie like this.