Menu
CoddyTech

Restart the Level

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

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 icon

Challenge

Easy

A fall should restart the level the player is in and count the fall.

  1. Add using UnityEngine.SceneManagement; and change the count to private static int falls;, so a reload keeps it.
  2. In Update(), when player.position.y < fallY, do falls++; and load SceneManager.GetActiveScene().name.

Press Play and walk off an edge in both levels: Falls: 1, then Falls: 2. 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
    }
}

All lessons in Building Real Games

Practice on your own: Unity playground