Menu
CoddyTech

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 icon

Challenge

Medium

Keep the best run in best.json.

  1. In GameManager.cs, add a [System.Serializable] class BestRun with public ints wave and kills.
  2. Start loads it from best.json in Application.persistentDataPath with JsonUtility, if the file exists.
  3. At game over, a higher wave, or the same wave with more kills, becomes the best and is saved; bestText reads Best: 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);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Game Architecture in Unity

Practice on your own: Unity playground