简体   繁体   中英

Deserialization Error: InvalidCastException: Cannot cast from source type to destination type

I have this problem and I'm not sure how to solve it... I tried plenty of things and can't find something similar online for help.

Note: Another Scene uses a Script with saving and using the same .dat file, not sure if that's an issue though.

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 () {

}

It looks like your ScoreEntry class is using fields, not properties. I believe the serializer/deserializer requires properties. Try this:

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

    public int score {get;set;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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