Menu
CoddyTech

High Score

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

A high score is the best result of every game played, so it lives in PlayerPrefs, and it changes only when a game beats it. This pinball table checks when the last ball drains:

void GameOver()
{
    int best = PlayerPrefs.GetInt("PinballBest", 0);
    if (score > best)
    {
        PlayerPrefs.SetInt("PinballBest", score);
        PlayerPrefs.Save();
        Debug.Log("New high score: " + score);
    }
}

The comparison is what makes it a high score. Without it, a game of 300 after a best of 5000 would save 300, and the record would be gone. Compare with the saved best, not with something that starts at 0 in every game: a field that nothing loaded is 0 after every restart, so any score beats it. score > best keeps the old record on a tie, while score >= best would call a tie a new high score.

To show the high score during play, load it into a field in Start() and show that field. When a game beats it, update the field, PlayerPrefs and the text together, so the screen and the saved value never disagree.

challenge icon

Challenge

Medium

Keep a high score under the key BestPoints.

  1. In Start(), above ShowBest();, write best = PlayerPrefs.GetInt("BestPoints", 0);.
  2. In EndRound(), inside if (points > best): set best = points;, save it with PlayerPrefs.SetInt and PlayerPrefs.Save(), then call ShowBest(); and newBestText.SetActive(true);.

Press Play and pump a balloon (hold Space, let go), then Stop and Play: the best stays. Then Check.

Try it yourself

using UnityEngine;
using TMPro;

public class BalloonPump : MonoBehaviour
{
    public TMP_Text pointsText;
    public TMP_Text bestText;
    public GameObject newBestText;
    public float pumpRate = 20f;

    private float air;
    private int points;
    private int best;
    private bool roundOver;

    void Start()
    {
        ShowBest();
    }

    void Update()
    {
        if (roundOver) return;

        if (Input.GetKey(KeyCode.Space))
        {
            air += pumpRate * Time.deltaTime;
            transform.localScale = Vector3.one * (1f + air / 50f);
            pointsText.text = "Points: " + Mathf.FloorToInt(air);
            if (air > 100f)
            {
                points = 0;
                pointsText.text = "Pop! Points: 0";
                GetComponent<Renderer>().enabled = false;
                roundOver = true;
                EndRound();
            }
        }
        else if (Input.GetKeyUp(KeyCode.Space))
        {
            points = Mathf.FloorToInt(air);
            pointsText.text = "Points: " + points;
            roundOver = true;
            EndRound();
        }
    }

    void EndRound()
    {
        // Save a new best here
    }

    void ShowBest()
    {
        bestText.text = "Best: " + best;
    }
}

All lessons in Building Real Games

Practice on your own: Unity playground