Edited the code

Hi

Enjoying the course so far! I have taken on board what was discussed in previous videos and edited the code for the load next level.

void LoadsNextScene()

{

    int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;

    currentSceneIndex++;

    if (currentSceneIndex >= SceneManager.sceneCountInBuildSettings)

    {

        currentSceneIndex = 0;

    }

    SceneManager.LoadScene(currentSceneIndex);

}

I use the ++ modifier on the int to add one each time the method is called, I then removed the other int as I felt it was not needed and added more lines of code, I then use a >= if statement to check that we have not equalled or somehow passed the scene count and then reset the int back to 0. This was I can use the one int for all the code. Tested and works fine at the moment, maybe I will notice bugs further down the line.

Thanks

A smarter way to loop through the levels would be to use the module (%) operator:

int nextSceneIndex = (SceneManager.GetActiveScene().buildIndex + 1) % SceneManager.sceneCountInBuildSettings;
SceneManager.LoadScene(nextSceneIndex);
1 Like

Privacy & Terms