BinaryFormatter - Save and Load lists of data?
I have a party of characters and I would like to save each of those character's hp. With Testing I have gotten it to save a single character's hp but not sure how can I save all the characters.
Here is the character class which will contain the stats etc.
public class Character
{
[SerializeField] CharacterBase _base;
[SerializeField] int level;
public int HP { get; set; }
}
Then I have a CharacterParty class that I attached to a gameobject and this will contain all the characters in the party and call the saving and loading methods.
public class CharacterParty : MonoBehaviour
{
[SerializeField]List<Character> characters;
//Property for list of all characters
public List<Character> Characters
{
get
{
return characters;
}
}
//HEALTH SAVING & LOADING
public void SaveParty()
{
SaveManager.SaveMC(characters[0]);
}
public void LoadParty()
{
PartyData data = SaveManager.LoadMC();
characters[0].HP = data.hp;
}
}
My SaveManager class
public static class SaveManager
{
public static void SaveMC(Character mc)
{
BinaryFormatter formatter = new BinaryFormatter();
string path = Application.persistentDataPath + "/Save.save";
FileStream stream = new FileStream(path, FileMode.Create);
PartyData data = new PartyData(mc);
formatter.Serialize(stream, data);
stream.Close();
}
public static PartyData LoadMC()
{
string path = Application.persistentDataPath + "/Save.save";
if (File.Exists(path))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(path, FileMode.Open);
PartyData data = formatter.Deserialize(stream) as PartyData;
stream.Close();
return data;
}
else
{
Debug.Log("Save FIle not Found");
return null;
}
}
}
And then Finally, the class I use to store the data. which is PartyData class.
[System.Serializable]
public class PartyData
{
public int hp;
public PartyData(Character cParty)
{
hp = cParty.HP;
}
}
The above saves a single character's hp but I want to be able to save multiple character's hp. If you see in the CharacterParty class for save and load, I am simply saving and loading the character at index 0 only.
So if anyone can help me figure out how I can save multiple character's hp, I would really appreciate it. I'm sure it only needs a little tweaking in some parts of my code.