Hello everyone!
I’m having a little binary serialization problem and I hope someone can help. Using the following code, when I run my Save() function, it appears to run just fine and creates the proper file. When I run the Load() function, it runs but my Debug.Log I have set up in another script that directly reads the GameData.xxxx variables, all return their default/null values.
I should also add, if I run the game, alter all the variables, hit my “test save” (which applies all entry boxes / dropdown to GameData’s static variables), then hit “test load” which calls the Load() function (file names for both save and load are the same, verified), it does work! It is just when I set up a character, hit save, exit, start the game again, hit load, it recalls only default values.
Here is my GameManager script with accompanying GameData. Any advice would be much appreciated!
using UnityEngine;
using System.Collections;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
public class GameManager : MonoBehaviour {
public static GameManager game;
private readonly string fileSuffix = ".vgs"; //Viaticum Game Save
void Awake () {
if(!game){
DontDestroyOnLoad(gameObject);
game = this;
} else {
Destroy(gameObject);
}
}
public void Save(string fileName){
fileName = Application.persistentDataPath + "/" + fileName + fileSuffix;
Debug.Log("Save: " + fileName);
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(fileName, FileMode.OpenOrCreate);
bf.Serialize(file, GameData.data);
file.Close();
}
public void Load(string fileName){
fileName = Application.persistentDataPath + "/" + fileName + fileSuffix;
if (File.Exists(fileName)){
Debug.Log("Load: " + fileName);
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(fileName, FileMode.Open);
GameData.data = (GameData)bf.Deserialize(file);
} else {
Debug.Log("File not found: " + fileName);
}
}
}
[Serializable]
public class GameData
{
public static GameData data = new GameData();
public static string playerName;
public static int playerSex;
public static int playerClass;
public static int playerElement;
public static int playerSpecialty;
public static int playerLineage;
public static int playerHomeland;
public static int playerSkill;
public static int playerSpell;
public static int playerItem;
}
Have you tried putting the GameData constructor somewhere else (perhaps where you set the variables)? Seems kind of funky to construct an object within it's type's blueprints before any of the members get initialized. I mean just off the top of my head something like that wouldn't even work in C/++, but I don't know the finer details of the CLR for situations like this.
– robnwfoo