Menu
CoddyTech

Best Run

Part of the Building Real Games section of Coddy's Unity journey. Lesson 33 of 60.

The last step of the Endless Runner: the best run is kept in PlayerPrefs, the way the high score was, so it survives Run again and quitting the game.

challenge icon

Challenge

Medium

Save the best run under the key BestRun.

  1. Add private int best;. In Start(), load it with PlayerPrefs.GetInt("BestRun", 0) and show "Best: " + best + " m" in bestText.
  2. At the end of GameOver(), when Mathf.FloorToInt(distance) beats best, save it, show it and call newBestText.SetActive(true);.

Press Play, set a best, then beat it: New best! shows. Then Check.

Try it yourself

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;

public enum GameState { Playing, GameOver }

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;
    public GameObject gameOverPanel;
    public Button restartButton;
    public GameState state = GameState.Playing;
    public TMP_Text bestText;
    public GameObject newBestText;
    private float distance;

    void Awake()
    {
        Instance = this;
    }

    void Start()
    {
        restartButton.onClick.AddListener(Restart);
    }

    void Update()
    {
        if (state != GameState.Playing) return;

        speed = Mathf.Min(speed + speedUp * Time.deltaTime, maxSpeed);
        distance += speed * Time.deltaTime;
        distanceText.text = "Distance: " + Mathf.FloorToInt(distance) + " m";
    }

    public void GameOver()
    {
        state = GameState.GameOver;
        speed = 0f;
        gameOverPanel.SetActive(true);
    }

    void Restart()
    {
        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 Building Real Games

Practice on your own: Unity playground