Save & Load - PlayerPrefs

Saving and Loading Data using PlayerPrefs in Unity

Let’s take a look at PlayerPrefs to save and load data in Unity. PlayerPrefs is a basic save system designed to store player preferences. It can only save float, int, and string values. The data will be stored in the registry of the player’s platform without encryption, so each installation of the game will share a PlayerPrefs storage. Make sure to limit the data saved this way since cluttering the registry will cause optimization issues.

(Not in the mood for a step-by-step guide? Here's a GitHub repository for ya!)

With these in mind, we can understand why this could be a good way to save the user’s settings like resolution and audio volumes. On the flip side, we can see how these limitations would not be great for saving game data like players’ positions, stats, and inventory items. If you’re looking for a simple way to save game data, try using JSON or BinaryFormatter. You’ll be able to save a wider range of data types and have easier implementation by saving an object that carries all the data. To learn more about them, check out our tutorials on using JSON and BinaryFormatter to save and load data in Unity.

Now let’s go ahead and look at the implementation of PlayerPrefs. PlayerPrefs uses getters and setters for the three types of data it can store. Each data is stored with a key (which is a string to label the data) and a value. We’ll start with examples of setting the data. The setter will pass on the key and value like this: PlayerPrefs.SetFloat(string key, float value).


float masterVolume = 100;

       int graphicsQuality = 2;

       string playerColour = "green";


PlayerPrefs.SetFloat("masterVolume", masterVolume);

PlayerPrefs.SetInt("graphicsQuality", graphicsQuality);

PlayerPrefs.SetString("playerColour", playerColour);



After setting the keys and values of the data to be saved, make sure to use Save() to lock in the modified data.


PlayerPrefs.Save();



The getters for PlayerPrefs look a bit different. You can simply get a value using a key like this: PlayerPrefs.GetFloat(string key).

Or you can give it a default value if there are no saved data with that key like this: PlayerPrefs.GetFloat(string key, float value).

Here is an example of the different ways to use the getters.


masterVolume = PlayerPrefs.GetFloat(“masterVolume”);

int defaultGraphicsQuality = 2;

graphicsQuality = PlayerPrefs.GetInt(“graphicsQuality”, defaultGraphicsQuality);


playerColour = PlayerPrefs.GetString(“playerColour”, “green”);



There is also a way to check for data by using HasKey(string key), which will return a bool. This isn’t particularly useful as the getter has the ability to use default values, so it doesn’t matter if we check for data or not beforehand. But if you’d like to check for data, here’s how.


if(PlayerPrefs.HasKey(“masterVolume”))

Debug.Log(“Found masterVolume key in saved data.”);

else

Debug.Log(“masterVolume key not found.”);



All that’s left is deleting data. There are two ways to do this. One is to delete individual data using the key name.


PlayerPrefs.DeleteKey(“masterVolume”);



And the other way is to delete all of the saved keys and values.


PlayerPrefs.DeleteAll();

Using all of these tools, let’s create a script that can load, save, and delete data using PlayerPrefs. First, let’s set up the variables we’ll need.

float masterVolume;
int graphicsQuality;
string playerColour;

float defaultVolume = 100;
int defaultGraphicsQuality = 2;
string defaultPlayerColour = "green";

When the game start we should load any saved data or use the default values for these settings. Here is what our load method can look like.

void LoadSettings()
{
	masterVolume = PlayerPrefs.GetFloat("masterVolume", defaultVolume);
	graphicsQuality = PlayerPrefs.GetInt("graphicsQuality", defaultGraphicsQuality);
	playerColour = PlayerPrefs.GetString("playerColour", defaultPlayerColour);
}

Next is our saving method.

void SaveSettings()
{
	PlayerPrefs.SetFloat("masterVolume", masterVolume);
	PlayerPrefs.SetInt("graphicsQuality", graphicsQuality);
	PlayerPrefs.SetString("playerColour", playerColour);
}

And finally, to delete all our saved data.

void DeleteSettings()
{
	PlayerPrefs.DeleteAll();
}

Let’s combine all of this into one example script. Debug logs and inputs were added so you can jump right in to test it in the Unity editor!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SaveLoadPlayerPrefs : MonoBehaviour
{
    float masterVolume;
    int graphicsQuality;
    string playerColour;

    float defaultVolume = 100;
    int defaultGraphicsQuality = 2;
    string defaultPlayerColour = "green";

    void Start()
    {
        if (PlayerPrefs.HasKey("masterVolume"))
            Debug.Log("Saved data detected.");
        else
            Debug.Log("No saved data found. Using default load settings.");

        LoadSettings();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.L))
            LoadSettings();
        if (Input.GetKeyDown(KeyCode.S))
            SaveSettings();
        if (Input.GetKeyDown(KeyCode.D))
            DeleteSettings();
        if (Input.GetKeyDown(KeyCode.C))
            ChangeSettings();
    }

    void LoadSettings()
    {
        masterVolume = PlayerPrefs.GetFloat("masterVolume", defaultVolume);
        graphicsQuality = PlayerPrefs.GetInt("graphicsQuality", defaultGraphicsQuality);
        playerColour = PlayerPrefs.GetString("playerColour", defaultPlayerColour);

        Debug.Log("Load Settings. \nMaster Volume: " + masterVolume + ", Graphics Quality: " + graphicsQuality + ", Player Colour: " + playerColour);
    }

    void SaveSettings()
    {
        PlayerPrefs.SetFloat("masterVolume", masterVolume);
        PlayerPrefs.SetInt("graphicsQuality", graphicsQuality);
        PlayerPrefs.SetString("playerColour", playerColour);



        Debug.Log("Settings Saved.");
    }

    void DeleteSettings()
    {
        PlayerPrefs.DeleteAll();

        Debug.Log("Settings Deleted.");
    }

    void ChangeSettings()
    {
        masterVolume = 75;
        graphicsQuality = 1;
        playerColour = "orange";

        Debug.Log("Changed Settings. \nMaster Volume: " + masterVolume + ", Graphics Quality: " + graphicsQuality + ", Player Colour: " + playerColour);
    }
}

Aaaaand that’s PlayerPrefs! You can use it for saving game data if you must, but I highly recommend using it only for a smaller set of data like the game settings. Don’t forget there are other ways to save and load data, as shown in our tutorials on saving and loading using JSON and BinaryFormatter. If you want an extensive example of PlayerPrefs, check out this GitHub repository. Download the script and stick it on a game object to test out all the functionalities.

Level up your game development by finding more stuff to learn in our growing list of pixel-sized tutorials.