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