Getting an error while loading first scene after completing the second level

When i am finishing the second level i am getting an error. It loads the first scene anyway but it bugs me a little. here is the error:

and here is my code:



    private void LoadNextLevel()
    {
       
        int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
        //Debug.Log((SceneManager.sceneCountInBuildSettings - 1) == currentSceneIndex);
        if((SceneManager.sceneCountInBuildSettings - 1) >= currentSceneIndex )
        {
            SceneManager.LoadScene(0);
        } 
        SceneManager.LoadScene(currentSceneIndex + 1);
 

    }

both scenes are in the builder. the value in the Debug.Log Method returns true. as i mentioned it loads the map anyway. but i wanna get rid of the error.

i hope anyone can help :smiley:
Dubi

Welcome to the community @Daniel_Dubi

‘Both scenes’ suggests there are only 2 scenes. You are - according to the error - trying to load a 3rd

Your logic appears to be the wrong way round. You are checking if the number of scenes are more than the current scene index and if it is, load scene 0. You probably want something like this:

if (currentSceneIndex >= SceneManager,sceneCountInBuildSettings)
{
    SceneManager.LoadScene(0);
}

Also, the code after the if will still run. So, in your code, it will load scene 0 and then also try to load currentSceneIndex + 1. It works up to level 2 because it loads scene 0, then loads scene 0 + 1. All good. But next time it loads scene 0, and then loads scene 1 + 1. Not good

Thx a lot. You’ve got me the right hint :smiley:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms