Save a Number
Part of the Building Real Games section of Coddy's Unity journey. Lesson 22 of 56.
Every field starts from its default when the game starts. A player who collects 40 gems, quits and comes back tomorrow finds the gem count at 0, because quitting ends the game and everything in it. PlayerPrefs keeps small values on the player's device between games. Each value is stored under a key, a string you choose, with SetInt, SetFloat or SetString:
PlayerPrefs.SetString("PlayerName", "Robin");
PlayerPrefs.SetInt("LevelReached", 4);
PlayerPrefs.SetFloat("HoursPlayed", 2.5f);
PlayerPrefs.Save();To read a value back, call the Get of the same type with the same key. A key that was never saved reads as 0, 0 or an empty string, so on a player's first game this greeting shows an empty name and level 0:
void Start()
{
string player = PlayerPrefs.GetString("PlayerName");
int level = PlayerPrefs.GetInt("LevelReached");
Debug.Log(player + " is on level " + level);
}Keys are case sensitive: GetInt("levelreached") reads a key that was never saved and returns 0. A key holds one type, so read it with the Get that matches its Set. Save a value when it changes, not only when the game ends. Unity writes PlayerPrefs to disk when the game quits normally, and PlayerPrefs.Save() writes them at once, so a crash cannot lose them. A static field is no way around this: it lasts as long as the game is running, and quitting ends that too.
Challenge
MediumThe Hopper's JumpCounter counts its jumps on screen, but the count is a plain field, so every new game starts again at Jumps: 0. Make it a lifetime total that carries on from game to game:
- After each jump, save
jumpswithPlayerPrefs.SetIntunder the keyTotalJumps, and write it to disk withPlayerPrefs.Save(). - In
Start(), load the saved total intojumpsbefore the text shows it.
Press Play and jump a few times, then press Stop and Play again: the count carries on. Then Check.
Try it yourself
using UnityEngine;
using TMPro;
public class JumpCounter : MonoBehaviour
{
public TMP_Text jumpsText;
public float hop = 5f;
private Rigidbody rb;
private int jumps;
void Start()
{
rb = GetComponent<Rigidbody>();
ShowJumps();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rb.linearVelocity = Vector3.up * hop;
jumps++;
ShowJumps();
}
}
void ShowJumps()
{
jumpsText.text = "Jumps: " + jumps;
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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 Swap