繁体   English   中英

在Android上有时无法序列化到磁盘,但是在iOS上可以正常使用(Unity3d)

[英]Serializing to disk sometimes fails on Android, but on iOS works fine (Unity3d)

我正在使用二进制格式化程序并写入磁盘以保存游戏状态。 在iOS上,它可以完美运行,完全没有问题。

另一方面,在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有时无法保存,出于某些原因,currentSelectedSpells somethimes开头具有另一个咒语(我认为lastBossKilled会被解析为currentSelectedSpells),不能保存TAILPointsPointsAvailable。

再次,在iOS上,这很好用。 在我杀死应用程序后,在Android上,进步的机会很高。 我经常省很多钱。

您实际上每次都关闭流以进行冲洗吗?

您必须调用Close以确保所有数据都正确地写到基础流中。

https://msdn.microsoft.com/zh-CN/library/system.io.streamwriter.close(v=vs.110).aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM