C# Problem with saveing and loading in 2D
So I have made a 2D rpg game and I wanted to make a save and load function when ever the player steps on the save icon and pressed "E" but I keep getting this error.
Can anyone help me with this? My script is down below.
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary;
public class SaveAndLoad : MonoBehaviour {
private SaveData data;
public List<int> List1 = new List<int>();
public Vector3 xyz = new Vector3();
void Start () {
Load();
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
if (Input.GetButtonDown("Ineract")){
Save();
}
}
}
public void Save (){
if (!Directory.Exists(Application.dataPath + "/saves"))
Directory.CreateDirectory (Application.dataPath + "/saves");
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = file.Create (Application.dataPath + "/saves/SaveData.dat");
CopySaveData();
bf.Serialize(file, data);
file.Close();
}
public void CopySaveData(){
data.List1.Clear();
foreach(int i in List1){
data.List1.Add(i);
}
data.position = Vector3ToSerVector3 (xyz);
}
public void Load(){
if(File.Exists(Application.dataPath + "/saves/SaveData.dat")){
BinaryFormatter bf = BinaryFormatter();
FileStream file = File.Open(Application.dataPath + "/saves/SaveData.dat",FileMode.Open);
data = (savedata)bf.Deserialize(file);
CopyLoadData();
file.Close ();
}
}
public void CopyLoadData(){
List1.Clear();
foreach(int i in data.List1){
List1.Add(i);
}
xyz = SerVector3ToVector (data.position);
}
public static SerVector3 Vector3ToSerVector3(Vector3 V3){
SerVector3 SV3 = SerVector3();
SV3.x = V3.x;
SV3.y = V3.y;
SV3.z = V3.z;
return SV3;
}
public static Vector3 SerVector3ToVector(SerVector3 SV3){
Vector3 V3 = new Vector3 ();
V3.x = SV3.x;
V3.y = SV3.y;
V3.z = SV3.z;
return SV3;
}
}
[System.Serializable] public class savedata { public Vector3 position; public List List1 = new List(); } [System.Serializable] public class SerVector3 { public float x; public float y; public float z; }
Your answer
Follow this Question
Related Questions
No overload for method. 1 Answer
crouch attack collider 2d question 1 Answer
2D AI movement 0 Answers
Selecting a game object in Unity 2d 3 Answers
NullreferenceException dealing damage to a child of the enemy 0 Answers