【问题标题】:Deserialization Error: InvalidCastException: Cannot cast from source type to destination type反序列化错误:InvalidCastException:无法从源类型转换为目标类型
【发布时间】:2015-05-30 00:52:52
【问题描述】:

我遇到了这个问题,不知道如何解决...我尝试了很多方法,但在网上找不到类似的帮助。

注意:另一个场景使用脚本来保存和使用相同的 .dat 文件,但不确定这是否是个问题。

public GameObject[] top10 = new GameObject[10];

[System.Serializable]
public class ScoreEntry
{
    public string name;

    public int score;
}

// Use this for initialization
void Start () {
    if (File.Exists(Application.persistentDataPath + "/hiscores.dat"))
    {
        BinaryFormatter b = new BinaryFormatter();
        var f = File.Open(Application.persistentDataPath + "/hiscores.dat", FileMode.Open);

        List<ScoreEntry> hiScores = (List<ScoreEntry>)b.Deserialize(f);
        f.Close();

        for (int i = 0; i == hiScores.Count; i++)
            top10[i].GetComponent<TextMesh>().text += hiScores[i].name + " - " + hiScores[i].score;
    }
}

// Update is called once per frame
void Update () {

}

【问题讨论】:

    标签: c# unity3d deserialization


    【解决方案1】:

    看起来您的 ScoreEntry 类正在使用字段,而不是属性。我相信序列化器/反序列化器需要属性。试试这个:

    [System.Serializable]
    public class ScoreEntry
    {
        public string name {get;set;}
    
        public int score {get;set;}
    }
    

    【讨论】:

    • 现在出现此错误:SerializationException: serializationStream 支持查找,但其长度为 0 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.NoCheckDeserialize (System.IO.Stream serializationStream, System.Runtime.Remoting .Messaging.HeaderHandler 处理程序)(在 /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Runtime.Serialization.Formatters.Binary/BinaryFormatter.cs:155)
    • 您使用的是序列化的旧文件吗?尝试使用这个新的类更改(属性)创建一个新的序列化文件。如果您尝试反序列化旧版本,它可能没有正确序列化。该错误使文件看起来不包含任何数据。此链接answers.unity3d.com/questions/767580/… 建议I guess you didn't call formater.serialize in your Save() function.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    相关资源
    最近更新 更多