- Home /
Save Game loading Deserialization from disk
Hi all,
I've been pulling my hairs out over the following for a couple of days now. I managed to make it work fine for saving data to disc but can't seem to get the reverse to work.
I want to load back from the disc a file and deserialize it into:
public KeyValuePairLists<bool> boolKeyValuePairLists = new KeyValuePairLists<bool> ();
My loading method is:
public void LoadFromDisk(){
//the errors send back to this line but I can't see any wrong arguments ...
Serializer.Deserialize (this.name + "Bool.dat", boolKeyValuePairLists);
}
Followed by the Serializer class which contains:
public class Serializer{
//generic deserialization from disk method
public static void Deserialize<T>(string filename, ref KeyValuePairLists<T> data)
{
if (File.Exists (Application.dataPath + "/GameSave/" + filename)) {
BinaryFormatter bf = new BinaryFormatter ();
FileStream file = File.Open(Application.dataPath + "/GameSave/" + filename, FileMode.Open);
data = (KeyValuePairLists<T>) bf.Deserialize (file);
file.Close();
}
}
// deserialization overloads
private void Deserialize(string filename, ref KeyValuePairLists<bool> data)
{
Deserialize (filename, ref data);
}
}
So far I've managed to reduce all the errors down to:
Assets/Scripts/ScriptableObjects/DataPersistence/SaveData.cs(182,14): error CS1502: The best overloaded method match for `SaveData.Serializer.Deserialize<bool>(string, ref SaveData.KeyValuePairLists<bool>)' has some invalid arguments
Assets/Scripts/ScriptableObjects/DataPersistence/SaveData.cs(182,51): error CS1620: Argument `#2' is missing `ref' modifier
You have to use the ref keyword when calling the method, much like using the out keyword. ' Although to be honest, this seems like a bad way to retrieve data. A simple deserializer that outputs a generic object that can be converted after, and only takes an inco$$anonymous$$g string for path or filename seems way more versatile. This can basically only deserialize one type of data, ever. Whereas the other way, would work for any serializable data at all. I wrote a tutorial on it if you want to take a look. Simple Data Storage It is under Part 3: Serializing Complex Objects.
Thanks for the comment and link. Yes the system is the one from the Unity's adventure tutorial and can only store on type of data per $$anonymous$$eyValuePairLists. I have a question regarding serializable objects though. Can you serialize absolutely anything as long as you add the [serializable] keyword above the class name ? That sounds way to easy ...
Answer by TreyH · May 10, 2017 at 07:01 PM
It's telling you the problem, you need to include your "ref" keyword:
Serializer.Deserialize (this.name + "Bool.dat", ref boolKeyValuePairLists);