0

I am trying to serialize my integer but i get the following error:

InvalidCastException: Cannot cast from source type to destination type.

SaveLoad.Load() (at Assets/SaveLoad.cs:24) refers to another script that just loads it on awake loadgame.Awake() (at Assets/loadgame.cs:8) refers to

StatContainer.totalcoins = (int)bf.Deserialize(file);

I am new to data serialization can someone explain where my mistake is ?

using UnityEngine;
using System.Collections;
using System.Collections.Generic; 
using System.Runtime.Serialization.Formatters.Binary; 
using System.IO;

public static class SaveLoad {
//public static List<StatContainer> savedGames = new List<StatContainer>();

//it's static so we can call it from anywhere
public static void Save() {
    //SaveLoad.savedGames.Add(StatContainer.current);
    BinaryFormatter bf = new BinaryFormatter();
    //Application.persistentDataPath is a string, so if you wanted you can put that into debug.log if you want to know where save games are located
    FileStream file = File.Create (Application.persistentDataPath + "/savedGames.gd"); //you can call it anything you want
    bf.Serialize(file, StatContainer.current);
    file.Close();
}   

public static void Load() {
    if(File.Exists(Application.persistentDataPath + "/savedGames.gd")) {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Open(Application.persistentDataPath + "/savedGames.gd", FileMode.Open);
        StatContainer.totalcoins = (int)bf.Deserialize(file);
        file.Close();
        Debug.Log ("Loaded");
    }
}
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
Nikolay Atanasov
  • 215
  • 2
  • 12

1 Answers1

0

Call Debug.Log(bf.Deserialize(file)); to see what kind of object it's returning, because it's obviously not an int.

SilentSin
  • 1,026
  • 9
  • 18