I have a static PlayerData singleton which stores all the data for the player (gold, upgrades, heroes etc) but JsonUtility cannot serialise static or private methods so I have implemented a singleton with an intermediate SaveFile struct which is used in the serialisation.
PlayerData will have more complex objects likes HeroCollection etc but for now, I simply have a gold stat.
I am looking for a potentially better alternative solution or simply how to improve this.
Thanks.
struct SaveFile
{
public int Gold;
}
public class PlayerData
{
static PlayerData Instance = null;
// # - Private Attributes - #
int _Gold;
// ... Heroes
// ... Upgrades
// ... Etc
// # - - - - - - - #
// # - Public Static Attributes - #
public static int Gold { get { return Instance._Gold; } set { Instance._Gold = value; } }
// # - - - - - - - #
public static void Create(string json)
{
if (Instance == null)
Instance = FromJson(json);
}
public static string ToJson()
{
return JsonUtility.ToJson(
new SaveFile()
{
Gold = Instance._Gold
}
);
}
static PlayerData FromJson(string json)
{
SaveFile save = JsonUtility.FromJson<SaveFile>(json);
return new PlayerData()
{
_Gold = save.Gold
};
}
}