Menu
CoddyTech

Survival Night

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

A survivor stands in a dark field, and bats come for them all night, a new one every couple of seconds from one of the field's four corners. Each bat flies straight at the survivor, and the first one to reach them ends the night. A clock at the top counts the seconds to dawn: last until then and you win. A Pause button freezes everything, and when the night ends, Play again starts a new one.

The Player script, which walks the survivor with the Move action, is written. Write GameManager and Bat.

challenge icon

Challenge

Hard

The Inspector gives GameManager nightLength (15), spawnEvery (2), batPrefab, spawnPoints (the four corners), dawnText, pauseButton, pausePanel, endPanel, endText and restartButton.

  • It is a singleton (public static GameManager Instance), and it has a nested public enum State with Playing, Paused, Won and Lost, and a public State state. The night starts in Playing.
  • While Playing: the seconds left go down from nightLength, shown rounded up, as Dawn in 12; every spawnEvery seconds a bat appears at one of spawnPoints, picked at random. When no time is left, the night is Won.
  • pauseButton switches Playing to Paused and back. Paused stops the game's time (Time.timeScale 0) and shows pausePanel; Playing again restarts the time and hides it. In Won or Lost it does nothing.
  • A public Lose() makes a Playing night Lost.
  • Won and Lost stop the game's time and show endPanel with endText reading You survived the night! or The bats got you.
  • restartButton starts a new night by loading the scene again.

The Inspector gives Bat speed (2) and reach (1). While the night is Playing, a bat flies toward the player (tagged Player) at speed, keeping its own height. When it gets within reach of the player on the ground plane, it calls Lose().

Press Play and try to last until dawn, then Check.

Try it yourself

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

public class GameManager : MonoBehaviour
{
    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;
}
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