Menu
CoddyTech

Load with a Default

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

A key that was never saved reads as 0, and 0 is a poor start for some values. A racing game lets the player choose how many computer rivals join a race, and a new player should race against 3. Every Get takes a second argument, the default, which it returns when the key is missing:

int rivals = PlayerPrefs.GetInt("Rivals", 3);
string driver = PlayerPrefs.GetString("Driver", "Rookie");

Once the player saves 0 rivals to practise alone, GetInt("Rivals", 3) returns 0: the default fills in a missing key only. That is why if (rivals == 0) rivals = 3; is the wrong way to give a default. It cannot tell a saved 0 from nothing saved, and puts 3 rivals back into every practice race.

PlayerPrefs.HasKey(key) answers whether a key has ever been saved, whatever its value, so it tells a first game from a later one. This game greets a new driver:

void Start()
{
    if (!PlayerPrefs.HasKey("Driver"))
    {
        Debug.Log("First race! Pick a name in the garage.");
    }
    string driver = PlayerPrefs.GetString("Driver", "Rookie");
    Debug.Log("Driver: " + driver);
}

Ask HasKey before any code that saves the key: from the first save on, it answers true until the key is removed with PlayerPrefs.DeleteKey.

challenge icon

Challenge

Medium

Give a new player 5 free credits and a welcome.

  1. In Start(), load with a default: credits = PlayerPrefs.GetInt("Credits", 5);.
  2. Replace welcomeText.SetActive(false); with welcomeText.SetActive(!PlayerPrefs.HasKey("Credits"));.

Press Play and play a game, then Stop and Play: the welcome is gone. Then Check.

Try it yourself

using UnityEngine;
using TMPro;

public class ArcadeCredits : MonoBehaviour
{
    public TMP_Text creditsText;
    public GameObject welcomeText;
    private int credits;

    void Start()
    {
        credits = PlayerPrefs.GetInt("Credits");
        welcomeText.SetActive(false);
        ShowCredits();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && credits > 0)
        {
            credits--;
            PlayerPrefs.SetInt("Credits", credits);
            PlayerPrefs.Save();
            ShowCredits();
        }
    }

    void ShowCredits()
    {
        creditsText.text = "Credits: " + credits;
    }
}

All lessons in Building Real Games

Practice on your own: Unity playground