I'm using binary formatter and writing to disk to save my game state. On iOS this works perfectly, no issues at all.
On Android on the other hand this fails. The progress is lost, two variables are lost, two others are saved, everything goes bonkers.
What might be my issue? Here is the code to serialize/deserialize:
// path to file
private static string saveFileName = "047.bin";
// Deserialization function
public GlobalState(SerializationInfo info, StreamingContext ctxt)
{
lastBossKilled = (int)info.GetValue("lastBoss", typeof(int));
currentlySelectedSpells = (SpellType[])info.GetValue("spells", typeof(SpellType[]));
learnedTalents = (int[])info.GetValue("talents", typeof(int[]));
talentPointsAvailable = (int)info.GetValue("talentPoints", typeof(int));
}
//Serialization function.
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
info.AddValue("lastBoss", lastBossKilled);
info.AddValue("spells", currentlySelectedSpells);
info.AddValue("talents", learnedTalents);
info.AddValue("talentPoints", talentPointsAvailable);
}
Here is the code that loads and saves state:
public void SaveState()
{
using (StreamWriter sw = new StreamWriter(Application.persistentDataPath + "/" + saveFileName)) {
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(sw.BaseStream, this);
}
}
public static GlobalState LoadState()
{
try {
using (StreamReader sr = new StreamReader(Application.persistentDataPath + "/" + saveFileName)) {
BinaryFormatter bf = new BinaryFormatter();
GlobalState result = (GlobalState)bf.Deserialize(sr.BaseStream);
return result;
}
} catch (Exception e) {
return null;
}
}
And here is the constructor that gets called if the load returns null:
private GlobalState()
{
lastBossKilled = -1;
currentlySelectedSpells = new SpellType[] { SpellType.SlowHeal, SpellType.Renew, SpellType.None, SpellType.None };
learnedTalents = new int[] { 0, 0, 0, 0, 0, 0, 0, 0 };
talentPointsAvailable = 0;
}
Issues: lastBossKilled sometimes not getting saved, currentlySelectedSpells somethimes for some reason has another spell in the beginning (I feel that lastBossKilled is getting parsed as currentlySelectedSpells), talentPointsAvailable is not getting saved.
Again, on iOS this works just fine. On Android after I kill the app, the chance is very high that progress will get lost. I save a lot and often.
↧