Crash and Restart
Part of the Building Real Games section of Coddy's Unity journey. Lesson 31 of 56.
Challenge
MediumA crash ends the run, and a button starts the next one. Keep everything from the earlier lessons. The canvas has a hidden GameOverPanel with a RestartButton labelled Run again, and the scene fills two new fields of GameManager, gameOverPanel and restartButton. The Runner has a kinematic Rigidbody, so it gets trigger messages from the obstacles.
In GameManager:
- Above the class, declare
public enum GameState { Playing, GameOver }, and give the class a fieldpublic GameState statethat starts asPlaying. - Add
using UnityEngine.UI;,using UnityEngine.SceneManagement;,public GameObject gameOverPanel;andpublic Button restartButton;. - A public method
GameOver()setsstatetoGameOver, setsspeedto 0, which stops every obstacle, and shows the panel. Update()does nothing unless the state isPlaying, so the speed and the distance stop.- In
Start(), makerestartButtonreload the scene that is playing.
In Runner: when it enters a trigger tagged Obstacle, call GameManager.Instance.GameOver(). While the state is not Playing, the arrows do nothing.
In Spawner: spawn nothing while the state is not Playing.
Press Play, crash, and run again, then Check.
Try it yourself
using UnityEngine;
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;
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
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