Easy cross-platform data saving and loading for Unity
I like to make games that work both on desktop and in WebGL.
My games usually need to save data of some kind, like user settings or highscores. On desktop, I like to use SUCC, because it generates files in a convenient location and formatted in a beautiful way.
However, SUCC doesn't work in WebGL, so my cross-platform games can't use it.
PersistentData is a clean API for saving c# data. On desktop platforms, the data is saved as SUCC. On all other platforms, the data is serialized with Newtonsoft.Json, then stored in PlayerPrefs.
This means the desktop versions of your apps will have beautiful convenient SUCC data files, but your apps will still work perfectly on other platforms without you needing to write any platform-dependent code.
- Install SUCC via the package manager (Add package from git URL ->
https://github.com/JimmyCushnie/SUCC.git#unity
) - Install Newtonsoft.Json via the package manager (Add package by name ->
com.unity.nuget.newtonsoft-json
) - Install PersistentData via the package manager (Add package from git URL ->
https://github.com/JimmyCushnie/PersistentData.git
)
All of the functions from this library are in the PersistentData.GameValues
class. They all have xml documentation.
PersistentData's API is very similar to SUCC's DataFile API.
using PersistentData;
...
const string KEY_HIGHSCORE = "highscore";
void SaveHighscore(int score)
=> GameValues.Set(KEY_HIGHSCORE, score);
int LoadHighscore()
=> GameValues.Get(KEY_HIGHSCORE, defaultValue: 0);
When you're serializing a Complex Type, both the desktop and non-desktop serializers use attributes to determine what to serialize.
Desktop (SUCC):
- public fields and properties are serialized unless marked with the
[SUCC.DontSaveThis]
attribute - private fields and properties are serialized if and only if marked with the
[SUCC.SaveThis]
attribute
WebGL/other (Newtonsoft.Json):
- public fields and properties are serialized unless marked with the
[Newtonsoft.Json.JsonIgnore]
attribute - private fields and properties are serialized if and only if marked with the
[Newtonsoft.Json.JsonProperty]
attribute
In order to keep serialization consistent between platforms, it is recommended that you only save complex types without any of the above attributes on any members.