Menu
CoddyTech

The End of the Night

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

The last challenge finishes a whole game: a manager with states, a pause that stops time, two endings and a restart that sets the time scale back.

challenge icon

Challenge

Hard

Add a pause, two endings and a restart.

  1. pauseButton switches only Playing and Paused: Paused sets Time.timeScale to 0 and shows pausePanel, Playing undoes both.
  2. At 0 seconds the night is Won. Won or Lost: time scale 0, endPanel showing You survived the night! or The bats got you in endText.
  3. restartButton sets the time scale to 1 and reloads the scene.

Press Play, pause, lose, play again. Then Check.

Try it yourself

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;

public class GameManager : MonoBehaviour
{
    public enum State { Playing, Paused, Won, Lost }

    public static GameManager Instance;

    public float nightLength = 15f;
    public float spawnEvery = 2f;
    public GameObject batPrefab;
    public Transform[] spawnPoints;
    public TMP_Text dawnText;
    public Button pauseButton;
    public GameObject pausePanel;
    public GameObject endPanel;
    public TMP_Text endText;
    public Button restartButton;

    public State state;

    private float timeLeft;
    private float spawnTimer;

    void Awake()
    {
        Instance = this;
    }

    void Start()
    {
        state = State.Playing;
        timeLeft = nightLength;
        ShowDawn();
    }

    void Update()
    {
        if (state != State.Playing) return;

        timeLeft -= Time.deltaTime;
        spawnTimer += Time.deltaTime;
        if (spawnTimer >= spawnEvery)
        {
            spawnTimer -= spawnEvery;
            Transform point = spawnPoints[Random.Range(0, spawnPoints.Length)];
            Instantiate(batPrefab, point.position, Quaternion.identity);
        }
        ShowDawn();
    }

    public void Lose()
    {
        if (state != State.Playing) return;
        state = State.Lost;
    }

    void ShowDawn()
    {
        dawnText.text = "Dawn in " + Mathf.CeilToInt(timeLeft);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Building Real Games

Practice on your own: Unity playground