Darren A.
Darren A.

Reputation: 97

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

}

Upvotes: 1

Views: 1292

Answers (1)

ps2goat
ps2goat

Reputation: 8475

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;}
}

Upvotes: 1

Related Questions