Data Persistence: Save And Load Data With Unity’s PlayerPrefs
Aside from the ability to pause, sometimes a game also needs a way for players to save progress, too. Especially if it’s a long game that usually takes multiple sessions to finish. Luckily, Unity has provided an easy-to-use class to achieve just that.
PlayerPrefs is a C# class provided by Unity that has the ability to store values that can persist through multiple play sessions. PlayerPrefs can store 3 types of values: integer, float, and string value.
PlayerPrefs is useful for storing player preferences. Note that data stored via PlayerPrefs is unencrypted and should you need to save any sensitive information, it is recommended to encrypt it before saving, or use a different technique to store data.
How To Save Data In Unity
There are 3 types of values you can store using PlayerPrefs: integer, float, and string.
// Store a string value
PlayerPrefs.SetString("keyName1", "Some random text.");
// Store a float value
PlayerPrefs.SetFloat("keyName2", 123.45f);
// Store an integer value
PlayerPrefs.SetInt("keyName3", 654);
Code language: C# (cs)
The value set this way will be stored with an identifier or a key which you can use to retrieve the value later.
All values set via PlayerPrefs are saved on a local drive and persist through multiple play sessions. What this means is, even if you close the game and open it again, the values will not be deleted.
This is useful for storing player preferences such as settings or player’s stats, things that need to carry over across multiple play sessions.
Note that the Set functions do not store values right away. They will write values to the memory first, and then commit them to the disk when the game is quitting, i.e. during the OnApplicationQuit event.
If you want to force the game to write the data to disk right away, use PlayerPrefs.Save().
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SaveManager : MonoBehaviour
{
void Start()
{
PlayerPrefs.SetString("Key1String", "Test");
PlayerPrefs.SetFloat("Key3Float", 123.45f);
PlayerPrefs.SetInt("Key2Integer", 543);
PlayerPrefs.Save();
}
}
Code language: C# (cs)
PlayerPrefs.Save() forces the values set via the Set functions to be written to disk right away. This is useful in case of potential crashes that might happen.
How To Load Data In Unity
Now that we know how to save data, we also need to know how to retrieve it so it can be used in future play sessions.
// Get a string value with a specified key
PlayerPrefs.GetString("keyName1");
// Get a float value with a specified key
PlayerPrefs.GetFloat("keyName2");
// Get an integer value with a specified key
PlayerPrefs.GetInt("keyName3");
Code language: C# (cs)
Each of these functions will return a value of their respective type.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SaveManager : MonoBehaviour
{
void Start()
{
string stringData = PlayerPrefs.GetString("Key1String");
float floatData = PlayerPrefs.GetFloat("Key3Float");
int intData = PlayerPrefs.GetInt("Key2Integer");
Debug.Log("Key1String: " + stringData);
Debug.Log("Key3Float: " + floatData);
Debug.Log("Key2Integer: " + intData);
}
}
Code language: C# (cs)
The above example will print out the values as followed:
If the specified key doesn’t exist, the default value of each respective type will be returned instead.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SaveManager : MonoBehaviour
{
void Start()
{
string stringData = PlayerPrefs.GetString("RandomKey1");
float floatData = PlayerPrefs.GetFloat("RandomKey2");
int intData = PlayerPrefs.GetInt("RandomKey3");
Debug.Log("RandomKey1: " + stringData);
Debug.Log("RandomKey2: " + floatData);
Debug.Log("RandomKey3: " + intData);
}
}
Code language: C# (cs)
The default string value is an empty string and the default value for float type and integer type is 0 (zero).
If you don’t want this behavior, the default value can be manually set, too. By specifying a value in the Get function, it will return that value instead, if the specified key doesn’t exist.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SaveManager : MonoBehaviour
{
void Start()
{
string stringData = PlayerPrefs.GetString("RandomKey1", "This is the default string.");
float floatData = PlayerPrefs.GetFloat("RandomKey2", 2222.22f);
int intData = PlayerPrefs.GetInt("RandomKey3", 987);
Debug.Log("RandomKey1: " + stringData);
Debug.Log("RandomKey2: " + floatData);
Debug.Log("RandomKey3: " + intData);
}
}
Code language: C# (cs)
How To Delete Persistent Data In Unity
Data set via PlayerPrefs can be deleted by simply calling DeleteKey or DeleteAll.
PlayerPrefs.DeleteKey("KeyToDelete");
Code language: C# (cs)
DeleteKey deletes the value tied to a specified key. If the key doesn’t exist, nothing will happen.
Code language: C# (cs)PlayerPrefs.DeleteAll();
DeleteAll wipes everything set via PlayerPrefs for the running application.
How To Check If Data Exist
There will be times when you want to just check if a value exists. For that, you can use the HasKey function.
PlayerPrefs.HasKey("KeyToCheck");
Code language: C# (cs)
HasKey returns true if the key exists, and returns false if it doesn’t.
Caveat
Although PlayerPrefs is easy to use and can be used to do many things. It is not quite secure.
As you can see from the image above, anything set via PlayerPrefs will not be encrypted and can be read easily. You’re encouraged to not store any sensitive information such as access tokens or API keys this way. Or, if you have to, you must manually encrypt the value first.
To find out where the values are stored in each platform, visit the official PlayerPrefs documentation page.
Alternative
While PlayerPrefs is easy to use, it can only store 3 types of values: string, float, and integer. This isn’t ideal if you want more structured player preferences.
For better control of how your data is structured, I recommend Easy Save – The Complete Save Data & Serialization Asset.
Easy Save is a paid asset available on Unity Asset Store. It allows for much better control over how you want to serialize data while keeping it easy to use.
It is very well-documented and comes with a data encryption feature. The best thing about Easy Save is: You can store data of almost all types available in Unity, and the data can be uploaded to cloud storage or can even be serialized to a spreadsheet.
If you’re willing to spend money, I really highly recommend this asset as it will make your life much, much easier and it can save a lot of time.
Conclusion
You can save and load data quickly through the use of functions available in PlayerPrefs class provided by Unity.
Use PlayerPrefs.SetInt(), PlayerPrefs.SetFloat(), or PlayerPrefs.SetString() to write values that persist through multiple play sessions.
Use PlayerPrefs.GetInt(), PlayerPrefs.GetFloat(), PlayerPrefs.GetString() to get values saved via the Set functions.
PlayerPrefs.DeleteKey() and PlayerPrefsDeleteAll() are used to delete a key or everything, respectively.
Data set via PlayerPrefs functions are not encrypted so sensitive data are not encouraged to be saved this way. A paid asset named Easy Save is highly recommended as it offers more control and has much more features than PlayerPrefs.
Attribution
Floppy disk icon used in the featured image made by Freepik from www.flaticon.com