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

Capture reference to loaded scene

Discussion in 'Scripting' started by MacFBG, Nov 16, 2016.

  1. MacFBG

    MacFBG

    Joined:
    Jan 23, 2016
    Posts:
    18
    Hey folks,

    I was wondering if there was anyway to capture a reference to a recently loaded Scene?

    I'm using:

    Code (CSharp):
    1. SceneManager.LoadSceneAsync("RockPrototype", LoadSceneMode.Additive)
    To load up a new scene, now because I've got several instances of the "RockPrototype" scene, I can't simple find it by name and even it's BuildIndex wouldn't be much use to me. I have considered using the hashcode for each scene as a unique identifier. However if I was going to use this I would need to capture that hashcode at the point I'm loading the scene.

    Any thoughts?
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Try:
    Code (csharp):
    1.  
    2. void Awake()
    3. {
    4.     SceneManager.sceneLoaded += this.OnSceneLoaded;
    5. }
    6.  
    7. void OnSceneLoaded(Scene scene, LoadSceneMode sceneMode)
    8. {
    9.    Debug.Log("New scene loaded: " + scene);
    10. }
    11.  
     
  3. MacFBG

    MacFBG

    Joined:
    Jan 23, 2016
    Posts:
    18
    Thanks for the reply!

    So this doesn't quite solve my problem, there will be let's say 20 scenes being loaded up, of varying types. What I want to be able to do is in pseudo:

    - Load Rock scene = newRockScene (this loads the scene and stores a reference to the scene)
    - newRockScene.Rocks = something (now I can do stuff with that scene)

    If I was to use your example, I would have several scenes firing the same code all at once.
     
  4. TJHeuvel-net

    TJHeuvel-net

    Joined:
    Jul 31, 2012
    Posts:
    818
  5. _met44

    _met44

    Joined:
    Jun 1, 2013
    Posts:
    633
    You can check which scene fired the callback, for example:

    Code (CSharp):
    1. switch (scene.name)
    2. {
    3.    case "RockPrototype": DoRockPrototypeStuff(); break;
    4.    case "WoodPrototype": DoWoodPrototypeStuff(); break;
    5. }
    6.  
    (or if you have many scenes, can use a dictionnary to avoid the huge switch block etc)