Search Unity

Question DontDestroyOnLoad ONLY First Object

Discussion in 'Scripting' started by SuccessFail, Sep 19, 2021.

  1. SuccessFail

    SuccessFail

    Joined:
    Jan 14, 2021
    Posts:
    23
    I have a GameObject I want to keep between scenes and the whole
    Code (CSharp):
    1. if (!exists)
    2.         {
    3.             exists = true;
    4.             DontDestroyOnLoad(transform.gameObject);
    5.         }
    6.         else
    7.         {
    8.             Destroy(gameObject);
    9.         }
    thing works great, except when I re-enter a scene it deletes the old object and keeps the new object. I want it to keep the old one as it holds some information. Does anyone know how to achieve this?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Don't use this construct. I know there's like ten zillion tutorials out there advocating it but as you can see, it has ALL kinds of weird edge cases.

    Instead, use this construct, and DO NOT put anything in the scene:

    Simple Singleton (UnitySingleton):

    Some super-simple Singleton examples to take and modify:

    Simple Unity3D Singleton (no predefined data):

    https://gist.github.com/kurtdekker/775bb97614047072f7004d6fb9ccce30

    Unity3D Singleton with a Prefab (or a ScriptableObject) used for predefined data:

    https://gist.github.com/kurtdekker/2f07be6f6a844cf82110fc42a774a625

    These are pure-code solutions, do not put anything into any scene, just access it via .Instance!

    If it is a GameManager, when the game is over, make a function in that singleton that Destroys itself so the next time you access it you get a fresh one, something like:

    Code (csharp):
    1. public void DestroyThyself()
    2. {
    3.    Destroy(gameObject);
    4.    Instance = null;    // because destroy doesn't happen until end of frame
    5. }