Storing Persistent Data in Unity

The PlayerPrefs class provides a simple way to persistently store scalar data in Unity. I like to use my own abstraction layer at this point in case I want to change the storage approach at some point. Also, the layer harmonizes very well with the RuntimeStorage class I developed.

Integer, float and string values can be stored. Thanks to overloading, there are actually only two different methods: Get and Set. With Get, it is always mandatory to assign a default value (otherwise the overload will not work). That value will be returned if no stored values are found.

The class also ensures that values are not repeatedly written to the storage medium. That is, if you update several values in succession, then the storage is triggered only once in the LateUpdate method.

using UnityEngine;

public class PersistentStorage : MonoBehaviour
{
    private bool _isDirty = false;

    private void LateUpdate()
    {
        if (_isDirty) {
            PlayerPrefs.Save();
            _isDirty = false;
        }
    }

    public void Set(string key, int value)
    {
        PlayerPrefs.SetInt(key, value);
        _isDirty = true;
    }

    public void Set(string key, float value)
    {
        PlayerPrefs.SetFloat(key, value);
        _isDirty = true;
    }

    public void Set(string key, string value)
    {
        PlayerPrefs.SetString(key, value);
        _isDirty = true;
    }

    public int Get(string key, int defaultValue)
    {
        return PlayerPrefs.GetInt(key, defaultValue);
    }

    public float Get(string key, float defaultValue)
    {
        return PlayerPrefs.GetFloat(key, defaultValue);
    }

    public string Get(string key, string defaultValue)
    {
        return PlayerPrefs.GetString(key, defaultValue);
    }
}

By the way, it is best to create the whole thing as a Singleton. This way you can access the class more easily.

You can then save values like this:

PersistentStorage.Instance.Set("someInteger", 42);
PersistentStorage.Instance.Set("someFloat", 0.815);
PersistentStorage.Instance.Set("someString", "foo");

And this is how you retrieve them:

PersistentStorage.Instance.Get("someInteger", 0);
PersistentStorage.Instance.Get("someFloat", 0.0f);
PersistentStorage.Instance.Get("someString", "");

There are no comments yet.