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
HardAdd a pause, two endings and a restart.
pauseButtonswitches only Playing and Paused: Paused setsTime.timeScaleto 0 and showspausePanel, Playing undoes both.- At 0 seconds the night is Won. Won or Lost: time scale 0,
endPanelshowingYou survived the night!orThe bats got youinendText. restartButtonsets 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);
}
}
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 SwapPractice on your own: Unity playground