I want to save Lists that are using a class and then use BinaryFormatter to make it a .dat file.
I have no idea how I would do this
I want to save Lists that are using a class and then use BinaryFormatter to make it a .dat file.
I have no idea how I would do this
First of all, the class needs to be marked as Serializable. You do this by adding [System.Serializable] over the header:
using UnityEngine;
using System.Collections;
[System.Serializable]
public class YourClass {
//...
}
If the class holds any Unity-specific variable types like Vector3, Transform, Mesh and so on, you need IsirializationSurrogates for those types, but that’s another story. For now, I will just assume that the class only contains stuff like int, string, float etc.
Okay, we now need a class that acts as your save file. Since you said you wanted to save lists, I will just assume that we will want to serialize three lists. So the class would look like this:
using UnityEngine;
using System.Collections;
[System.Serializable]
public class SaveFileClass{
public string saveFileName;
public List<YourClass> yourClassList1;
public List<YourClass> yourClassList2;
public List<YourClass> yourClassList3;
}
You need to assign the lists you have to these variable by yourself, of course.
Next up is the actual serialization and writing to file:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Runtime.Serialization;
public static class SaveLoad {
//it's static so we can call it from anywhere
public static void Save(saveFile SaveFileClass ) {
BinaryFormatter bf = new BinaryFormatter();
//Application.persistentDataPath is a string, so if you wanted you can put that into debug.log if you want to know where save games are located
FileStream file = File.Create (Application.persistentDataPath + "/" + saveFile.savefileName + ".dat"); //you can call it anything you want
bf.Serialize(file, saveFile );
file.Close();
Debug.Log("Saved File: " + saveFile.savefileName );
}
public static SaveFileClass Load(string fileToLoad) {
if(File.Exists(Application.persistentDataPath + "/" + fileToLoad + ".dat")) {
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/" + fileToLoad + ".dat", FileMode.Open);
SaveFileClass loadedFile = new SaveFileClass ();
loadedFile = (SaveFileClass )bf.Deserialize(file);
file.Close();
Debug.Log("Loaded File: " + loadedFile .savefileName );
}
}
}
You can now serialize your lists like this:
SaveFileClass saveFile = new SaveFileClass();
saveFile .saveFileName = "My new Save File";
//saveFile .yourClassList1 = !?!
//assign your lists to the class
SaveLoad.Save(saveFile);
Loading works similar:
SaveFileClass loadedFile = SaveLoad.Load("My new Save File");
//??? = loadedFile.yourClassList1;
//access the deserialized lists however you want