Dict of interfaces serialization issue [C#, Unity]

36 Views Asked by At

I'm trying to make a save system for my project. I want binary serialization, and I'm trying to use BuinaryFormatter. I Have no error when performing save, but if I call load, I get this error:

SerializationException: Type 'TheCompany.SaveSystem.ISaveData' in Assembly 'TheCompany.SaveSystem, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

Load and save code looks so:

        public void Save()
        {
            GameSave gameSave = new GameSave(GetSaveData());
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            FileStream file = File.Create(Application.persistentDataPath + "/gamesave.save");
            binaryFormatter.Serialize(file, gameSave);
            file.Close();
        }

        public GameSave Load()
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/gamesave.save",        FileMode.Open);
            GameSave gameSave = (GameSave)binaryFormatter.Deserialize(file);
            file.Close();
            return gameSave;
        }

Data class:

    [Serializable]
    public class GameSave 
    {
        private Dictionary<Type, HashSet<ISaveData>> _savedata;

        public Dictionary<Type, HashSet<ISaveData>> Savedata => _savedata;

        public GameSave(Dictionary<Type, HashSet<ISaveData>> savedata)
        {
            _savedata = savedata;
        }
    }

ISaveData:

    public interface ISaveData : ISerializable
    {

    }

I'm sure all of ISaveData implementations are marked with [Serializable] Other way, an error would occurs on save. In my tests _savedata contains only one key with Hashset of one element. When I'm trying to save only this one ISaveData in structure like this, its works completely fine.

    [Serializable]
    public class GameSave 
    {
        public ISaveData Savedata;
    }

Update: All my concrete implementations of ISaveData are structs. When I changed them into classes, the exception disappeared.

0

There are 0 best solutions below