繁体   English   中英

反序列化错误:InvalidCastException:无法从源类型转换为目标类型

[英]Deserialization Error: InvalidCastException: Cannot cast from source type to destination type

我遇到了这个问题,我不确定如何解决...我尝试了很多事情,但在网上找不到类似的内容来寻求帮助。

注意:另一个场景使用保存并使用相同.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 () {

}

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

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

    public int score {get;set;}
}

暂无
暂无

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

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