Menu
CoddyTech

Next Level

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

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

Make each goal open the next level.

  1. In Start(), show "Level " + level + " of " + levels in levelText: level is the active scene's buildIndex, levels is SceneManager.sceneCountInBuildSettings - 1.
  2. In OnTriggerEnter, for the Player, load buildIndex + 1, or 0 (the Menu) when that is not below sceneCountInBuildSettings.

Press Play and finish all three levels: the Menu comes back. 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
    }
}

All lessons in Building Real Games

Practice on your own: Unity playground