Survive
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 47 of 50.
Challenge
MediumLast 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.
Herogetspublic event Action Died, raised when its health reaches 0, after it turns itself off.- In
GameManager.cs, add a[System.Serializable]classBestRunwithpublic int waveandpublic int kills. GameManagerlistens to the hero'sDiedand toEnemy.Died, which counts this run's kills: subscribe inOnEnable, unsubscribe inOnDisable. InStartit loads the best run frombest.jsoninApplication.persistentDataPathwithJsonUtility, when that file exists, hides the panel, and makesrestartButtonrestart the game.- When the hero dies, stop the game (
Time.timeScale0). The run is the spawner'sWaveand 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 tobest.jsonwithJsonUtility.ToJson. Show the run inresultText, asWave 2, 7 kills, and the best inbestText, asBest: 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
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular Turret10Project: Arena Survivor
The HeroEnemy Types