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
HardThe 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 nestedpublic enum StatewithPlaying,Paused,WonandLost, and apublic State state. The night starts in Playing. - While Playing: the seconds left go down from
nightLength, shown rounded up, asDawn in 12; everyspawnEveryseconds a bat appears at one ofspawnPoints, picked at random. When no time is left, the night is Won. pauseButtonswitches Playing to Paused and back. Paused stops the game's time (Time.timeScale0) and showspausePanel; 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
endPanelwithendTextreadingYou survived the night!orThe bats got you. restartButtonstarts 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;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Building Real Games
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input Swap