I'm using Unity 2017 and wish to serialize save game data like so:
public void Save(Statistics data)
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath
+ "/playerInfo.dat");
bf.Serialize(file, data);
file.Close();
}
The LevelData
class is marked Serializable
and contains only string
s and int
s. The class that implements IPersistentData
meets those requirements too.
I did look for the problem and found that I should set an environment variable in my Awake
method that I did, but that didn't solve anything. I'm using Windows 10 as operating system to develop on but the game will be made for Android.
When attempting to save, I always get this exception
SerializationException: Unexpected binary element: 255 System.Runtime.Serialization.Formatters.Binary.ObjectReader.ReadObject (BinaryElement element, System.IO.BinaryReader reader, System.Int64& objectId, System.Object& value, System.Runtime.Serialization.SerializationInfo& info)
Any sort of advice is welcome to get around the issue.
EDIT
Updating after trying the hints of Programmer: The class I wish to serialize:
[Serializable]
public class Statistics
{
public int LastPlayedLevel;
public Statistics()
{
MusicVolume = 1f;
SFXVolume = 1f;
LevelDatas = new List<LevelData>();
LastPlayedLevel = 1;
}
public float MusicVolume;
public float SFXVolume;
public List<LevelData> LevelDatas;
}
And the LevelData
:
[Serializable]
public class LevelData
{
public LevelData(int levelNumber,string name)
{
this.LevelNumber = levelNumber;
this.Name = name;
this.BestPercent = 0;
this.DeathCount = 0;
}
public int LevelNumber;
public string Name;
public int BestPercent;
public uint DeathCount;
}