Search Unity

GetSceneByName returns null

Discussion in 'Scripting' started by EstragonHelmer, Jan 17, 2019.

  1. EstragonHelmer

    EstragonHelmer

    Joined:
    Oct 26, 2017
    Posts:
    12
    To switch between levels, I built some code that takes the current scene name (formatted like 'Level 1') and increases the number on the end each time, so it can load the next level.

    When I load the next level, I check that a scene with that name is valid, and if so load it. If not, it returns to the menu instead.

    GetSceneByName keeps returning null, so when I check if the scene is valid, it says it's not. Obviously the scene is there, it's in the build settings, but the code keeps returning null.

    In the documentation there's a bit I don't understand about GetSceneByName checking an exact file path in some cases, or just looking at the end of the scene names...

    Code (CSharp):
    1. //check if next level exists
    2. Scene sceneCheck = SceneManager.GetSceneByName (nextLevel);
    3. if (sceneCheck.IsValid ())
    4.     SceneManager.LoadScene (nextLevel);
    5. else
    6.     SceneManager.LoadScene ("Level Select");
     
    Last edited: Jan 17, 2019
  2. nilsdr

    nilsdr

    Joined:
    Oct 24, 2017
    Posts:
    374
    two things, the docs state it searches through the scenes that are already loaded, so I wouldn't expect the above to work?

    so, what are you passing as nextLevel? and are the scenes in build settings?
     
  3. EstragonHelmer

    EstragonHelmer

    Joined:
    Oct 26, 2017
    Posts:
    12
    All the scenes are in the build settings. 'nextLevel' is a string that is the name of the level I want to load. But sometimes, it won't exist, which is why I'm trying to use the isValid check on it first.

    Ok, yes. I just tested it with a different scene, and realised maybe I was doing it differently when it worked. I have changed that code quite a few times now.
     
    Last edited: Jan 17, 2019