What is binaryformatter and where can I find a very simple example about it? Same with filestream.
BinaryFormatter is used to serialize an object (meaning it converts it to one long stream of 1s and 0s), and deserialize it (converting that stream back to its usual form with all data intact), and is typically used with to save data to the hard disk so it can be loaded again after the game is closed and started up again.
There’s a good tutorial here that goes over using BinaryFormatter and FileStream to save and load data, but it’s a bit long.
As for simpler examples, these are bits of my own SaveManager class I ended up with after watching that tutorial:
public class SaveManager
{
private SaveGlob saveGlob; // the Dictionary used to save and load data to/from disk
protected string savePath;
public SaveManager()
{
this.savePath = Application.persistentDataPath + "/save.dat";
this.saveGlob = new SaveGlob();
this.loadDataFromDisk();
}
/**
* Saves the save data to the disk
*/
public void saveDataToDisk()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(savePath);
bf.Serialize(file, saveGlob);
file.Close();
}
/**
* Loads the save data from the disk
*/
public void loadDataFromDisk()
{
if(File.Exists(savePath))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(savePath, FileMode.Open);
this.saveGlob = (SaveGlob)bf.Deserialize(file);
file.Close();
}
}
where SaveGlob is a class with the [System.Serializable] attribute that holds whatever data you need to save. It could conceivably look as simple as this, or it could hold entire arrays or even dictionaries of data:
[System.Serializable]
public class SaveGlob
{
public int level;
public float health;
public bool isHardMode;
}