Menu
CoddyTech

Survive

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 47 of 50.

challenge icon

Challenge

Medium

Last step: the run ends, and the best run is kept. Keep everything from the earlier lessons. The canvas has a hidden GameOverPanel with ResultText, BestText and a RestartButton labelled Fight again, and the GameManager object has your GameManager script, with hero, spawner, gameOverPanel, resultText, bestText and restartButton set in the Inspector.

  • Hero gets public event Action Died, raised when its health reaches 0, after it turns itself off.
  • In GameManager.cs, add a [System.Serializable] class BestRun with public int wave and public int kills.
  • GameManager listens to the hero's Died and to Enemy.Died, which counts this run's kills: subscribe in OnEnable, unsubscribe in OnDisable. In Start it loads the best run from best.json in Application.persistentDataPath with JsonUtility, when that file exists, hides the panel, and makes restartButton restart the game.
  • When the hero dies, stop the game (Time.timeScale 0). The run is the spawner's Wave and the kills. It is a new best when it reached a higher wave, or the same wave with more kills: then it becomes the best and is saved to best.json with JsonUtility.ToJson. Show the run in resultText, as Wave 2, 7 kills, and the best in bestText, as Best: wave 3, 12 kills, then show the panel.
  • The restart sets the time scale back to 1 and loads the scene again.

Press Play and fight until you fall, then try to beat your best. Then Check.

Try it yourself

using UnityEngine;

public class GameManager : MonoBehaviour
{
    // A later lesson fills this in: the end of the run and the best run.
}

All lessons in Game Architecture in Unity