我使用二进制格式化程序并写入磁盘以保存我的游戏状态。在iOS上,这个功能完美无缺,完全没有问题。序列化到磁盘有时在Android上失败,但在iOS上工作正常(Unity3d)
另一方面在Android上失败。失去了进展,失去了两个变量,另外两个被拯救了,一切都变得焦躁不安。
可能是我的问题?下面是序列化的代码/反序列化:
// 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);
}
这里是加载和保存状态代码:
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;
}
}
,这里是如果负载返回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;
}
问题:lastBossKilled有时候没有得到保存,目前选择由于某种原因,有些事情在开始时有另一个咒语(我觉得lastBossKilled被解析为curre ntlySelectedSpells),talentPointsAvailable没有得到保存。
再次,在iOS上,这工作得很好。在我杀了应用程序后,在Android上,进度将会丢失的机会非常高。我经常节省很多。
2015-08-25
Dvole