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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

DontDestroyOnLoad() only works for root GameObjects or components on root GameObjects.

Discussion in 'Scripting' started by ToastYwasTaken, Mar 6, 2020.

  1. ToastYwasTaken

    ToastYwasTaken

    Joined:
    Oct 31, 2019
    Posts:
    3
    Hey, so i know DontDestroyOnLoad() can't be used on child objects, but that's the only way i thought my problem could be solved, maybe someone here has a better idea:

    I have a timer, that i want to keep across the levels. So when changing Scenes with Scenemanager the Timer gets reset and i can't use DontDestroyOnLoad() because my Timer is a child of a canvas (it has to be child of canvas, right?).
     
  2. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    906
    If your timer is a UI component it would need to be in a canvas to render, yes.
    There's nothing stopping you from calling DontDestroyOnLoad on the canvas though, which is what I would do if I needed some UI to persist through scene switches.
     
    ToastYwasTaken likes this.
  3. ToastYwasTaken

    ToastYwasTaken

    Joined:
    Oct 31, 2019
    Posts:
    3
    I tried DontDestroyOnLoad(transform.parent) or with transform.root but that doesn't work aswell :/
     
  4. ThermalFusion

    ThermalFusion

    Joined:
    May 1, 2011
    Posts:
    906
    The information you provide is very sparse, what is not working?
    If the thread title is some error message you receive when trying to call DontDestroyOnLoad, I would assume you're calling it on some object with a parent.
    If you still get that error with transform.root I'm not sure what's going on.
     
  5. ToastYwasTaken

    ToastYwasTaken

    Joined:
    Oct 31, 2019
    Posts:
    3
    In the png you can see my hierachy structure. The script is attached to the "Timer". In Awake() i'm just doing DontDestroyOnLoad(transform.root) or whatever else i already tried.
    The problem is still, that the timer resets whenever changing scenes
     

    Attached Files:

  6. VSMGames

    VSMGames

    Joined:
    Jan 12, 2020
    Posts:
    47
    Some ideas I would suggest looking into:
    • Making a separate script and gameobject for the timer value with DontDestroyOnLoad. Assuming you have script on timer under the canvas for value. This way you can have a new canvas and timer text on every scene displaying the value from different Timer gameobject which doesn't get destroyed when the new scene gets loaded.
    • Attaching the DontDestroyOnLoad script component to Canvas.
    • Creating a separate canvas for only the timer if you have other UI elements under it which you want to be removed when the new scene gets loaded.