Search Unity

Multiple Scenes and persistent GameObjects

Discussion in 'Scripting' started by rcober, Aug 30, 2014.

  1. rcober

    rcober

    Joined:
    Jan 26, 2013
    Posts:
    52
    I am starting to add multiple scenes to my project.

    How should I handle 'cross' scene objects, like the hero, camera, gamemanager, etc?
    I was planning to mark them Object.DontDestroyOnLoad. but what about during design time...

    I want them in the scene during design time, so I can quickly playtest each scene as it is built.

    Should I just have them in each scene and then mark them as inactive, except in the first one, when doing a final build?

    Just wondering what the "standard approach" is for this....

    Thanks for any feedback
     
  2. jnoffke

    jnoffke

    Joined:
    Nov 26, 2013
    Posts:
    31
    On the object you want to live between scenes just add a MonoBehaviour that keeps a static reference to itself. If the static instance is null in Awake the set the reference to the object, otherwise just destroy it.

    Code (CSharp):
    1. public class GameManager : MonoBehaviour
    2. {
    3.     private static GameManager s_Instance = null;
    4.  
    5.     void Awake()
    6.     {
    7.         if (s_Instance == null)
    8.         {
    9.             s_Instance = this;
    10.             DontDestroyOnLoad(gameObject);
    11.  
    12.             //Initialization code goes here[/INDENT]
    13.         }
    14.         else
    15.         {
    16.             Destroy(gameObject);
    17.         }
    18.     }
    19. }
     
    Last edited: Aug 30, 2014