Skip to main content

Stash

Overview

This module is for storing data with encryption on Unity's PlayerPrefs or PersistentPath

Installing

  • Import package from Package Manager UI

How to use

  • Create a Stash object with unique identifier. It means you can have multiple Stash objects that enabled you to separate data.
var stash = Stash.PlayerPrefs("myStash", OnStashError);
// or var stash = Stash.PersistentPath("myStash", OnStashError);

void OnStashError(StashError error) // if Stash couldn't be created, you can observe it with OnStashError callback
{
Debug.LogError(error);
}
  • To get a value from your stash:
myInteger = stash.Get("myInteger", 42);
  • To set a value from your stash:
stash.Set("myInteger", myInteger)
info

for custom classes make sure you added System.Serializable attribute

[System.Serializable]
public class Foo
{
public int bar;
}

Stash Usage

Initialize

Initialize local stash object with given unique identifier. Either at PlayerPrefs or PersistentPath location. Register a method for error handling. If you want to save manually, you need to specify it.

 stash = Stash.PlayerPrefs(stashId, OnStashError);
// or stash = Stash.PersistentPath(stashId, OnStashError);

void OnStashError(StashError error)
{
Debug.LogError(error);
}

Set

You can save any object supported by binary formatter. int,byte,float,string,classes,struct etc. Set<T>(string key, T value) creates or updates given key-value pair

 stash.Set("someInteger", 5);
GameConfig writeConfig = new GameConfig();
stash.Set("gameConfig", writeConfig);

Get

For fail safe Get<T>(string key, T defaultValue) method requires defaultValue
If given key-value pair is not exist then defaultValue will be returned

 int integer = stash.Get("someInteger" , 0);
GameConfig readConfig = stash.Get("gameConfig", new GameConfig());

Has

You can check if stash has a value for given key.

if (stash.Has("someInteger"))
{
// someInteger exists in the stash
}

Save Stash

If you created a stash without autosave, stash won't be saved to disk until you call stash.Save() method. stash.Save() blocks UIThread until operation is completed.

danger

Dont save huge files(10 mb or more) when processing exit message (OS) may suspend your save operation you may end up with broken save file.

// can be called any time during the game.
stash.Save();

// on focus changes
private void OnApplicationFocus(bool hasFocus)
{
if (!hasFocus)
{
stash.Save();
}
}

// on application suspended (home button) - make sure stash is saved.
private void OnApplicationPause(bool pause)
{
if (pause)
{
stash.Save();
}
}