Search Unity

Don't destroy on load

Discussion in 'Scripting' started by unity_rLrstvXScQEvow, Jun 17, 2019.

  1. unity_rLrstvXScQEvow

    unity_rLrstvXScQEvow

    Joined:
    Mar 4, 2019
    Posts:
    28
    Hello,
    I actually had the problem if my player dies my persistent GameMaster script doesn't find his UI to display the health. My thinking was to add these couple lines of code to my canvas to prevent it from destroying when my scene gets loaded, when the player dies.

    Code (CSharp):
    1.     private static DontDestroyOnLoad instance;
    2.  
    3.     void Awake()
    4.     {
    5.         if(instance == null)
    6.         {
    7.             instance = this;
    8.             DontDestroyOnLoad(instance);
    9.         }
    10.         else
    11.         {
    12.             Destroy(gameObject);
    13.         }
    14.     }
    Do it get issues with code later? Or is there a more comfortable way to do it?
     
  2. csofranz

    csofranz

    Joined:
    Apr 29, 2017
    Posts:
    1,556
    That is a singleton with Scene persistance. If that is what you want, it looks fine. But if you go that route, you will not be able to have two or more player instances in the same scene.

    -ch
     
  3. Magiichan

    Magiichan

    Joined:
    Jan 5, 2014
    Posts:
    403