I am building a game in unity. I have a DataStorage parent class that is a singleton that I serialize/deserialize to save/load progress.
It looks like this:
public class DataStored
{
// Properties
public PlayerData Player { get; set; } = new PlayerData();
public EnvironmentData Environ { get; set; } = new EnvironmentData();
// Singleton
private static DataStored current;
public static DataStored Current
{
get
{
if (current == null)
{
current = new DataStored();
}
return current;
}
set
{
current = value;
}
}
}
I load the data like this:
...
DataStored.Current = (DataStored)bf.Deserialize(file);
...
This all works fine. And I can release my game. However, if I then need to add a new property to the DataStored singleton, e.g.:
public AppSettings Settings { get; set; } = new AppSettings();
Then this value is set initially, but then as soon as I load the game data, using the deserialize line of code above, it gets set to null (presumably because when I saved the singleton the property did not exist). What I was hoping for was the singleton would realise the property was null and then create a new instance of AppSettings for that property.
Is the only way around this to expand the code for each property I add, as follows? e.g.
private PlayerStatsData stats;
public PlayerStatsData Stats
{
get { return stats ??= new PlayerStatsData(); }
}
I am guessing using default auto-properties ignores the instantiation if the class object is deserialized rather than constructed a fresh?
My motivation for asking this question is the wish to reduce 3 lines of code to 1 line of code for each of the many new properties I will be creating.