Menu
CoddyTech

Load with a Default

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

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

The arcade machine keeps a player's credits under the key Credits: Space plays a game for one credit, and the credits left are saved after each game. New players are not handled yet:

  • A player with nothing saved starts with 5 free credits. A player who has used every credit has 0 saved, and starts with 0, not 5.
  • The welcomeText object (Welcome! Here are 5 free credits) shows only to a player who has no Credits saved. Every other player does not see it.

Press Play and play a game, then press Stop and Play again: 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;
    }
}
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