- Home /
Question by
lilscarecrow · Dec 05, 2015 at 06:16 PM ·
arrayserializationclasscustom
Custom Class Array Serialization Problem
I am having trouble figuring out how to serialize data correctly when it comes to custom class arrays. I currently have a persistent info object that contains a nested serialization method to save all of the persistent data in the game. I want to save an array of enemies remaining in a scene and have an enemy script that I attach to all enemies. So I have a successful Enemy[] to pass through, but every time I try and serialize, I get a bunch of errors like end of stream and such. Is there a better way to achieve what I am looking for?
public void Save(string path)
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/" + path + ".dat");
PlayerData data = new PlayerData();
//put in info for data
data.setData();
bf.Serialize(file, data);
file.Close();
}
public bool Load(string path)
{
if(File.Exists(Application.persistentDataPath + "/" + path + ".dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/" + path + ".dat", FileMode.Open);
PlayerData data = (PlayerData) bf.Deserialize(file);
file.Close();
//take info from file into data
data.getData();
return true;
}
return false;
}
[Serializable]
class PlayerData
{
private int enemyCount;
private Enemy[] enemies;
public void setData()
{
enemyCount = control.getEnemyCount();
enemies = control.getEnemyArray();
}
public void getData()
{
control.setEnemyCount(enemyCount);
control.setEnemyArray(enemies);
}
}
Comment