- Home /
Generic Save and Load using BinaryFormatter not working
I don't know what I'm doing wrong. Everytime I call method load I get the default(T) which is 0 or null, even if I used the method save before. This is my code for loading and saving
public static void save<T>(string path, T obj) {
// Create/Open the file and write the obj
using (FileStream file = File.Open(Application.persistentDataPath + "/" + path, FileMode.Create)) {
var bf = new BinaryFormatter();
bf.Serialize(file, obj);
}
}
public static T load<T>(string path) {
var data = default(T);
// If file exists
if(File.Exists(Application.persistentDataPath + path)) {
// Open and read the class data
using (FileStream file = File.Open(Application.persistentDataPath + "/" + path, FileMode.Open)) {
var bf = new BinaryFormatter();
data = (T)bf.Deserialize(file);
}
}
return data;
}
If I have tryed to load and save plain ints and objects of this class
[Serializable]
public class bundle {
public int m = 0;
}
There are no errors, file is getting created and it's content is this for the object of class bundle
^@^A^@^@^@ÿÿÿÿ^A^@^@^@^@^@^@^@^L^B^@^@^@^OAssembly-CSharp^E^A^@^@^@^Fbundle^A^@^@^@^Am^@^H^B^@^@^@^@^@^@^@^K
So I guess save method is correct.
Thanks in advance!
Answer by Ebunix · Aug 03, 2015 at 12:05 PM
Looks like you are missing the /
in line 13. I think it should be
if(File.Exists(Application.persistentDataPath + "/" + path)) {
Last week I had => ins$$anonymous$$d of >=.
Now I was missing a /.
Just shoot me.
Your answer
Follow this Question
Related Questions
Can you make Mesh manipulations persistent? 2 Answers
How to tell android to open a file 0 Answers
Persistent data, Save file doesn't come out as hoped 1 Answer
How to script a Save/Load game option 17 Answers