Thanks in advance
.I can’t seem to get my Save/Load script to work :(. I try to use Unity serialization for this ,but alas when I hit the Load button I strangely get the values that my Game Master had in the beginning, before I even made this script!?
Notes:
- This script is attached to Game Master object.
- This object travels between scenes using a singleton design pattern.
- Please don’t tell me to use Player Prefs, I plan to add more variables and I want to learn !!
- Sorry, new to Unity Answers don’t know how to post my script properly :/.
- I have tried both using File.Create and File.Open for my save method, same result.
- I have found the file on my computer, so the the save method does create one.
using UnityEngine;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.UI;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class SaveLoad : MonoBehaviour {
public static SaveLoad control;
public float Armour;
public int Credits;
public Text Score;
void Awake(){
if (control == null) {
control = this;
DontDestroyOnLoad (gameObject);
} else if (control != this) {
Destroy(gameObject);
}
}
void Update(){
if (Score == null) {
Debug.Log("No Score Counter!!");
}
control.Score.text ="Credits: " +Credits.ToString();
}
public static void KillPlayer(Player player){
Application.LoadLevel("Menu");
}
public static void KillEnemy(Enemy Enemy){
Destroy (Enemy.gameObject);
}
public void Save(){
if (File.Exists (Application.persistentDataPath + "GameInfo.dat")) {
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Open(Application.persistentDataPath + "GameInfo.dat", FileMode.Open);
Debug.Log (Application.persistentDataPath);
PlayerData data = new PlayerData ();
data.Armour = Armour;
data.Credits = Credits;
bf.Serialize (file, data);
file.Close ();
Debug.Log ("Save");
}
}
public void Load(){
Debug.Log (Application.persistentDataPath);
if(File.Exists(Application.persistentDataPath + "GameInfo.dat")){
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "GameInfo.dat", FileMode.Open);
PlayerData data = (PlayerData)bf.Deserialize(file);
Debug.Log ("Load");
file.Close();
Armour = data.Armour;
Credits = data.Credits;
}
}
[System.Serializable]
public class PlayerData{
public float Armour;
public int Credits;
}
}