Menu
CoddyTech

Next Level

Part of the Building Real Games section of Coddy's Unity journey. Lesson 19 of 56.

Each scene in the build's scene list has a number, its build index: 0 for the first, 1 for the next, and so on. LoadScene takes that number as well as a name, and SceneManager.sceneCountInBuildSettings says how many scenes the list holds. With the levels in order in the list, the next level is the active scene's index plus 1. This exit loads it, and after the last level it stops:

void OnTriggerEnter(Collider other)
{
    if (!other.CompareTag("Player")) return;
    int next = SceneManager.GetActiveScene().buildIndex + 1;
    if (next < SceneManager.sceneCountInBuildSettings)
    {
        SceneManager.LoadScene(next);
    }
    else
    {
        Debug.Log("You finished the game!");
    }
}

With four scenes, the indexes are 0 to 3 and sceneCountInBuildSettings is 4, so on the last level next is 4, one past the end. That is why the test is next < sceneCountInBuildSettings: LoadScene(4) would load nothing and log Unity's error Cannot load scene: Invalid scene name (empty string) and invalid build index 4.

One exit script now serves every level, and none of them names a scene. To add a level, you add its scene to the list; to change the order, you drag the scenes around in the list.

challenge icon

Challenge

Easy

The build lists four scenes: Menu (index 0), then Level1, Level2 and Level3. The Menu's Play button opens Level1, and the arrows walk the Player (both ready). Each level has a gold Goal with the Goal script. Write it without naming any scene:

  • In Start, show this level's number and the number of levels in levelText, as Level 2 of 3. The Menu is not a level.
  • When the Player (tagged Player) reaches the goal, load the next level in the list. After the last level, go back to the Menu.

Press Play, play through all three levels, then Check.

Try it yourself

using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;

public class Goal : MonoBehaviour
{
    public TMP_Text levelText;

    void Start()
    {
        // show "Level 2 of 3": this level's number and how many levels there are
    }

    void OnTriggerEnter(Collider other)
    {
        // the player reached the goal: load the next level, or the menu after the last one
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Building Real Games