Restart the Level
Part of the Building Real Games section of Coddy's Unity journey. Lesson 18 of 56.
The quickest way to reset a level is to load it again. SceneManager.GetActiveScene() returns the scene that is open now, and its name (or its buildIndex) is what LoadScene takes. This Restart button on a game-over panel calls:
public void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}Unity destroys the open scene and builds it again from the scene file. Every object is back where the scene put it, a crate the player knocked over included, every field has its Inspector value again, and Awake and Start run again. No code has to put things back one by one. Because the button asks for the active scene instead of a name such as "Level3", the same script restarts any level it is placed in.
A static field is not part of the scene: it belongs to the class, so a reload leaves it as it was. A private static float bestTime; keeps the best time across restarts, while a normal private float time; starts again from 0 with the new scene. GameManager.Instance is static as well: after a reload it points at the destroyed GameManager until the new one's Awake sets it.
Challenge
EasyTwo levels, Level1 and Level2, each with a Level object holding the LevelRestart script. The arrows walk the Player, and the gold block in Level1 loads Level2 (both ready). Finish LevelRestart.cs:
- When the player drops below
fallY(-3), add 1 tofallsand restart the level the player is in: a fall in Level2 restarts Level2. fallscounts every fall of the game, so it must survive the reload. Start already shows it, asFalls: 1.
Press Play, walk off an edge in both levels, then Check.
Try it yourself
using UnityEngine;
using TMPro;
public class LevelRestart : MonoBehaviour
{
public Transform player;
public TMP_Text fallsText;
public float fallY = -3f;
private int falls;
void Start()
{
fallsText.text = "Falls: " + falls;
}
void Update()
{
// below fallY: count the fall and restart the level the player is in
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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 Swap