How to get BuildIndex from scene name?

I am trying to get the BuildIndex of a scene by name.

Scene nextScene = SceneManager.GetSceneByName("Scene1");
GameControllerMain.nextLevel = nextScene.buildIndex;
 Debug.Log(sceneName + " Index:"+GameControllerMain.nextLevel);

The debug however spits out -1 every time…

“Scene1” is the name of the scene file within “Assets/Scenes/”.

The scene has already been added to build settings as well.

SceneManager.GetSceneByName can only get scenes added to the SceneManager, which is to say only the loaded scenes.

I’m gonna say that again, because the documentation doesn’t do a good job of explaining it. Only scenes currently loaded and active are added to the SceneManager. SceneManager manages active scenes.

As it currently stands, there’s no good way to do what you want to do. SceneUtility.GetBuildIndexByScenePath can do it if you have the path, not just the name, but it’s definitely not ideal. Might work for you, though.

I managed to figure this out. Here you go, future googlers:

private static string NameFromIndex(int BuildIndex)
{
    string path = SceneUtility.GetScenePathByBuildIndex(BuildIndex);
    int slash = path.LastIndexOf('/');
    string name = path.Substring(slash + 1);
    int dot = name.LastIndexOf('.');
    return name.Substring(0, dot);
}

Was your scene loaded from an AssetBundle? If so, it is the proper behaviour according to their documentation : Unity - Scripting API: SceneManagement.Scene.buildIndex

SceneManager.GetActiveScene().buildIndex