Keep the Best Run
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 60 of 64.
Arena Survivor is complete: an abstract Enemy with two kinds, IDamageable for every hit, waves from a ScriptableObject, pickups behind an interface, a HUD that only listens and, last, a JSON save of the best run.
Challenge
MediumKeep the best run in best.json.
- In
GameManager.cs, add a[System.Serializable]classBestRunwith public intswaveandkills. Startloads it frombest.jsoninApplication.persistentDataPathwithJsonUtility, if the file exists.- At game over, a higher wave, or the same wave with more kills, becomes the best and is saved;
bestTextreadsBest: wave 3, 12 kills.
Press Play and fall twice: the best stays. Then Check.
Try it yourself
using System.IO;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using TMPro;
public class GameManager : MonoBehaviour
{
[SerializeField] private Hero hero;
[SerializeField] private WaveSpawner spawner;
[SerializeField] private GameObject gameOverPanel;
[SerializeField] private TMP_Text resultText;
[SerializeField] private TMP_Text bestText;
[SerializeField] private Button restartButton;
private int kills;
void OnEnable()
{
hero.Died += GameOver;
Enemy.Died += CountKill;
}
void OnDisable()
{
hero.Died -= GameOver;
Enemy.Died -= CountKill;
}
void Start()
{
gameOverPanel.SetActive(false);
restartButton.onClick.AddListener(Restart);
}
void CountKill(Enemy enemy)
{
kills++;
}
void GameOver()
{
Time.timeScale = 0f;
int wave = spawner.Wave;
resultText.text = "Wave " + wave + ", " + kills + " kills";
gameOverPanel.SetActive(true);
}
void Restart()
{
Time.timeScale = 1f;
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Game Architecture in Unity
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular TurretRecap: Twin Cannon4Serialized Data
Serializable ClassesLists in the InspectorEnums in the InspectorRecap: Loot TableRecap: Roll the Loot7State Machines
States as ClassesThe Alert StateA State MachineTransitionsEnemy BrainsThe Knight AttacksRecap: Door States10Project: Arena Survivor
The HeroEnemy Types2Interfaces in Unity
IDamageableInterfaces and TryGetComponentGetComponentsRecap: Interact KeyRecap: Nearest in ReachPractice on your own: Unity playground