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
EasyMake each goal open the next level.
- In
Start(), show"Level " + level + " of " + levelsinlevelText:levelis the active scene'sbuildIndex,levelsisSceneManager.sceneCountInBuildSettings - 1. - In
OnTriggerEnter, for the Player, loadbuildIndex + 1, or0(the Menu) when that is not belowsceneCountInBuildSettings.
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
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input SwapPractice on your own: Unity playground