Menu
CoddyTech

Crash Ends the Run

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

challenge icon

Challenge

Medium

A crash should stop the run.

  1. Above GameManager, declare public enum GameState { Playing, GameOver }; inside, add public GameState state = GameState.Playing;.
  2. public void GameOver() sets state to GameState.GameOver and speed to 0, and shows gameOverPanel.
  3. Runner calls GameManager.Instance.GameOver() on a trigger tagged Obstacle. GameManager, Runner and Spawner start Update() with a return unless Playing.

Press Play and crash: everything stops. Then Check.

Try it yourself

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
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;
    public GameObject gameOverPanel;
    public Button restartButton;
    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

Practice on your own: Unity playground