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
MediumKeep a high score under the key BestPoints.
- In
Start(), aboveShowBest();, writebest = PlayerPrefs.GetInt("BestPoints", 0);. - In
EndRound(), insideif (points > best): setbest = points;, save it withPlayerPrefs.SetIntandPlayerPrefs.Save(), then callShowBest();andnewBestText.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
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input SwapPractice on your own: Unity playground