Alternative Implementation

Rather than pre-calculating the next scene index, I just compared the scene index to load against the build count - 1, then handled circling to the front in the else condition.

    void LoadNextLevel()
    {
        if (_currentSceneIndex < SceneManager.sceneCountInBuildSettings - 1)
        {
            SceneManager.LoadScene(_currentSceneIndex + 1);
        }
        else
        {
            SceneManager.LoadScene(0);
        }
    }

Basically what this says is, if there are, say, 3 total levels in my scene, and I’m on Scene 3 (index of 2), it will look at the scene count, subtract one to get the index value, and move to the else condition (reload scene index 0) since 2 is not less than 2. If I were on scene index 0 or 1, it would return as true and proceed to the next scene in index order.

It’s essentially identical to Rick’s solution, just a different way to write the same thing. (I cached the _currentSceneIndex in Awake(), if you’re wondering where that part of the code is.)

Privacy & Terms