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

Assigning Scene Objects to DontDestroyOnLoad Object?

Discussion in 'Scripting' started by Kalliber95, Feb 22, 2021.

  1. Kalliber95

    Kalliber95

    Joined:
    Mar 27, 2015
    Posts:
    19
    Heya folks.

    I'm playing around with DontDestroyOnLoad and enabling a component if a particular scene is loaded.

    When the component wakes it assigns things like objects that it uses such as cameras and UI elements.

    What I've noticed is that however its not referencing the objects within the scene (it has a reference just not the scene specific one) nor can I manually add the objects via inspector to the DontDestroyOnLoad object.

    When I try to access something like the Main cam (For closing a menu and switching priorities via a UI button click(). ) it pops an null reference.

    Any ideas or am I missing something key about DontDestroyOnLoad objects interactions within scene objects?

    Here's the inspector at the Null reference




     
  2. NicBischoff

    NicBischoff

    Joined:
    Mar 19, 2014
    Posts:
    204
    If the objects don't exist in that scene then you won't be able to reference them.
    All that DontDestroyOnLoad does it makes the object resident between scenes but it does not make its references resident, they still exist in their original scene. You would need to make them also resident or parent them to this DontDestroyOnLoad object.
     
    Joe-Censored likes this.
  3. Kalliber95

    Kalliber95

    Joined:
    Mar 27, 2015
    Posts:
    19
    Would it be possible to make the game manager be a resident of the scene it loads into?

    Im having the player make a selection then load the scene with that selection as the choice.
     
  4. reachdabeach

    reachdabeach

    Joined:
    Jan 28, 2021
    Posts:
    70
    I am doing something similar to this using a singleton class that isn't a MonoBehavior but is called by them. You can create another class with public class static variable/functions/properties and values in them are globally available. I also subscribe to the scene change event in that class so that I can handle some things in various scenes even if they don't have a component script related to it.
     
  5. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    If you need a bunch of GameObjects to stick around that all reference each other, my suggestion is to stop using DontDestroyOnLoad. Make them their own scene, use additive scene loading/unloading, and just don't unload that scene when you switch scenes.