To start with. Im kinda new to scripting so I tryed to make save/load system for my game.
Because I didnt know how to make it, I watched this video, and copyed most of it and adjusted for my needs
The code is taken from this unity live tutorial session “http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/persistence-data-saving-loading” And I need help to fix this error I get.
The error "InvalidCastException: Cannot cast from source type to destination type
LevelLoad.Load () (at Assets/Scripts/LevelLoad.cs:69)
This is the Load sctipt.
To see where is the “error” Skip to the //Shows error here
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class LevelLoad : MonoBehaviour {
private int CHDoneNR;
private GameObject Box;
void Awake ()
{
Load ();
}
void Start()
{
switch (CHDoneNR) {
//Deleted Switch code to shorten the question.
}
Debug.Log (CHDoneNR);
}
public void Load()
{
if (File.Exists (Application.persistentDataPath + "/playerinfo.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/playerinfo.dat", FileMode.Open);
***//Shows error here***
PlayerData data = (PlayerData)bf.Deserialize(file);
file.Close();
CHDoneNR = data.LevelNR;
}
}
}
[Serializable]
class PlayerData
{
public int LevelNR;
}
This is the Save script
It seems that Save works fine, and is actualy saveing the file, but still I will add it here.
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class LevelSave : MonoBehaviour {
public int CHDoneNR;
void OnGUI() {
if (GUI.Button (new Rect (10, 10, 100, 30), "Save")) {
Save ();
}
}
public void Save()
{
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Create (Application.persistentDataPath + "/playerinfo.dat");
PlayerDataSave data = new PlayerDataSave ();
data.LevelNR = CHDoneNR;
bf.Serialize (file, data);
file.Close ();
}
}
[Serializable]
class PlayerDataSave
{
public int LevelNR;
}