Menu
CoddyTech

Crash and Restart

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

challenge icon

Challenge

Medium

A crash ends the run, and a button starts the next one. Keep everything from the earlier lessons. The canvas has a hidden GameOverPanel with a RestartButton labelled Run again, and the scene fills two new fields of GameManager, gameOverPanel and restartButton. The Runner has a kinematic Rigidbody, so it gets trigger messages from the obstacles.

In GameManager:

  • Above the class, declare public enum GameState { Playing, GameOver }, and give the class a field public GameState state that starts as Playing.
  • Add using UnityEngine.UI;, using UnityEngine.SceneManagement;, public GameObject gameOverPanel; and public Button restartButton;.
  • A public method GameOver() sets state to GameOver, sets speed to 0, which stops every obstacle, and shows the panel.
  • Update() does nothing unless the state is Playing, so the speed and the distance stop.
  • In Start(), make restartButton reload the scene that is playing.

In Runner: when it enters a trigger tagged Obstacle, call GameManager.Instance.GameOver(). While the state is not Playing, the arrows do nothing.

In Spawner: spawn nothing while the state is not Playing.

Press Play, crash, and run again, then Check.

Try it yourself

using UnityEngine;
using TMPro;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;

    public float speed = 10f;
    public float speedUp = 0.5f;
    public float maxSpeed = 20f;
    public TMP_Text distanceText;
    private float distance;

    void Awake()
    {
        Instance = this;
    }

    void Update()
    {
        speed = Mathf.Min(speed + speedUp * Time.deltaTime, maxSpeed);
        distance += speed * Time.deltaTime;
        distanceText.text = "Distance: " + Mathf.FloorToInt(distance) + " m";
    }
}

All lessons in Building Real Games