Unable to get the next scenes (buildIndex+1) name

Hey guys

I’ve spend a few hours trying to piece together something that I thought would be a basic ‘want’ that everyone would use but I cant seem to work it out or find enough online to piece it together.

I’m building levels (scenes) and inserting them as I go. After the nth level is the ‘Lose’ scene.

Logic
If the next scene (buildIndex+1) = the ‘Lose’ scene load my ‘Level01’ scene instead.
If the next scene (buildIndex+1) != the ‘Lose’ scene, then load it.

I tried all sorts of things without any joy. Although my code below doesn’t work, it does give a good idea what I am trying to achieve.

   public void LoadNextScene() {

        int nextscene = SceneManager.GetActiveScene().buildIndex + 1;
        string sname = SceneManager.GetSceneAt(nextscene).name;

        if (sname == "Lose") {                  //If the next scene is the 'Lose' scene ...
            SceneManager.LoadScene("Level01");  //start from Level01 again
            }
         //Goto the new next scene
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);

As always I am very grateful for your help and advice

Paul

A way around this is for my Lose scene just report its index number to my scene manager. That way I can just use logic.

One potential issue is the fact that you load one scene then the next. Put the other line in the if/else block.

 public void LoadNextScene() {
        int nextscene = SceneManager.GetActiveScene().buildIndex + 1;
        string sname = SceneManager.GetSceneAt(nextscene).name;
        if (sname == "Lose") {                  //If the next scene is the 'Lose' scene ...
            SceneManager.LoadScene("Level01");  //start from Level01 again
        } else {
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
        }

@Simple-Blue Yes you are right. I had an else in a previous version but not this one. There are still issues trying to do this though.

     int sceneIndex = SceneManager.GetActiveScene().buildIndex;
        int nxtIndex = 1;
        int nextscene = sceneIndex + nxtIndex;
        Debug.Log("nextscene: " + nextscene);

       string sname = SceneManager.GetSceneAt(nextscene).name;
     
        if (sname == "Lose") {                  //If the next scene is the 'Lose' scene ...
            SceneManager.LoadScene("Level01");  //start from Level01 again
            }
        else {
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
            }

        }

fixes that issue but it still does not work. It seems impossible to query the scene name unless its loaded.

 string sname = SceneManager.GetSceneAt(nextscene).name;

just does not work.

The only way I can see to do this is to create a List array from EditorBuildSettings.scenes and use that as a reference. It seems long winded to me. Am I missing something?

Have you found a way to fix it? I’m having the same problem right now