Be the first to post for 'Looping Through Levels'!

If you’re reading this, there probably aren’t very many posts yet. But don’t worry, you can be the first! Either create a new post or just reply to this one to say ‘hi’.

I figured out how to loop through the levels with the modulus operator, in case anyone else wants to know:

void LoadNextLevel()
{
int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
currentSceneIndex = (currentSceneIndex+1) % SceneManager.sceneCountInBuildSettings;
SceneManager.LoadScene(currentSceneIndex);
}

2 Likes

heres my version of events for the scene looping

added a couple of console outputs to inform user.

void ProcessDebugInputs()
{
   // if L key pressed load next level immediately
    if (Input.GetKeyDown(KeyCode.L))
    {
        int totalLevels = SceneManager.sceneCountInBuildSettings;   // gives total level count ( eg scenes 0,1,2 gives us 3)
        int currentlevel = SceneManager.GetActiveScene().buildIndex;  // this is the 0 based index of the current scene
       
        // if its the last scene just reload, otherwise load next
        if(currentlevel == totalLevels-1)
        {
            SceneManager.LoadScene(currentlevel);
            Debug.Log("Last scene in build so reloading same level");
        }
        else
        {
            SceneManager.LoadScene(currentlevel+1);
            Debug.Log("Another Scene vailable, Loading next level");
        }
    }

    // disable collision detection
    if (Input.GetKeyDown(KeyCode.C))
    {
        collisionsEnabledFlag = !collisionsEnabledFlag;
        Debug.Log("Collision detection enabled = " + collisionsEnabledFlag);
    }
}

When dealing with how the game loads the first level after beating your last. Are there any pros/cons to replacing “nextSceneIndex = 0; // loop back to start” with “LoadFirstLevel();” (What we used to reload on death).

scene%20loading%20solution

1 Like

Here was my code from the challenge:

    int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
    int nextSceneIndex = ((currentSceneIndex + 1) == SceneManager.sceneCountInBuildSettings)? 0 : currentSceneIndex + 1;
    SceneManager.LoadScene(nextSceneIndex);

Yet another version.

    private void LoadNextLevel()
    {
        state = State.Transcending;
        audioSource.Stop();
        audioSource.PlayOneShot(nextlevelClip);
        nextlevelParticles.Play();
        Invoke("LoadNextScene", loadLevelDelay); 
    }

    private void LoadSamelevel()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }

    private void LoadNextScene()
    {
        // check if there is another scene in build settings after this one
        if (SceneManager.GetActiveScene().buildIndex + 1 < SceneManager.sceneCountInBuildSettings)
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
        else
        {
            SceneManager.LoadScene(0);
        }
    }

Privacy & Terms