PlayerPrefs
TypeClass (static members)
NamespaceUnityEngine
Storesint, float, string

PlayerPrefs

PlayerPrefs saves small pieces of data that survive after the game is closed: volume settings, the high score, the last level reached. Each value is stored under a text key.

A row of labeled lockers. SetInt("HighScore", 500) puts 500 in the locker labeled "HighScore". GetInt("HighScore", 0) opens that locker, and if it's empty, gives you 0 instead. The lockers are good for small notes, not for storing a whole bookshelf.

Static Methods

MethodReturnsDescription
SetInt(string key, int value)voidStore an int.
GetInt(string key, int defaultValue = 0)intRead an int, or the default if the key doesn't exist.
SetFloat / GetFloatSame for floats.
SetString / GetStringSame for strings. Can hold JSON for simple structured data.
HasKey(string key)boolDoes this key exist?
DeleteKey(string key)voidRemove one key.
DeleteAll()voidRemove everything. Careful!
Save()voidWrite to disk now. (Unity also saves on normal quit.)

There's no bool type. Store 1 or 0 as an int.

Code Samples

High score

using UnityEngine;

public class ScoreKeeper : MonoBehaviour
{
    private const string HighScoreKey = "HighScore"; // one constant = no typos

    public int HighScore => PlayerPrefs.GetInt(HighScoreKey, 0);

    public void SubmitScore(int score)
    {
        if (score > HighScore)
        {
            PlayerPrefs.SetInt(HighScoreKey, score);
            PlayerPrefs.Save();
        }
    }
}

Settings: volume and a toggle

public void SetMusicVolume(float v)
{
    PlayerPrefs.SetFloat("MusicVolume", v);
}

public void SetShowFps(bool on)
{
    PlayerPrefs.SetInt("ShowFps", on ? 1 : 0);
}

void Start()
{
    float volume = PlayerPrefs.GetFloat("MusicVolume", 0.8f);
    bool showFps = PlayerPrefs.GetInt("ShowFps", 0) == 1;
}

Saving a small object as JSON

[System.Serializable]
public class SaveData
{
    public int level;
    public int coins;
}

void SaveGame(SaveData data)
{
    PlayerPrefs.SetString("Save", JsonUtility.ToJson(data));
    PlayerPrefs.Save();
}

SaveData LoadGame()
{
    string json = PlayerPrefs.GetString("Save", "");
    return string.IsNullOrEmpty(json) ? new SaveData() : JsonUtility.FromJson<SaveData>(json);
}

What happens at runtime

  1. Set... changes a value in memory. It's fast.
  2. The data is written to disk when you call Save() or the app quits normally. If the game crashes or is force-closed before that, unsaved changes are lost.
  3. Where it's stored depends on the platform: the registry on Windows, a .plist file on macOS, browser storage for WebGL, and so on.
  4. Data is stored per Company Name + Product Name (Player Settings). Changing those makes old data seem to disappear.

Common Mistakes

See also