Save multiple scriptableObjects in just one binary file

Hi, I have been trying to save and load several scriptable objects in just one binary file but with no success.

Any Idea of how to make this?

Thanks for you time.

Have you tried to serialize a list of these objects? I haven’t worked too much with saving data, but I think that should work. You would just need to make sure that index 0 is always referencing the Construction object and index 1 is always references the Hero object.

For example, inside the using statment in the save method you could probably do the following:

List<List<ScriptableObject>> objects = new List<List<ScriptableObject>>();
objects.Add(TownManager.instance.MyConstructions.Database);
objects.Add(HeroManager.instance.MyHeroDatabase.Database);

formatter.Serialize(saveFile, objects);

saveFile.Close();

and then in the using statment in the load method:

    List<List<ScriptableObject>> objects = 
        List<List<ScriptableObject>>formatter.Deserialize(saveFile);

    TownManager.instance.MyConstructions.Database = (List<Construction>) objects[0];
    HeroManager.instance.MyHeroDatabase.Database = (List<Hero>) objects[1];
    
    saveFile.Close();

I haven’t actually tested this code, so I’ve probably made a mistake somewhere. Assuming I haven’t and both the Construction and Hero class inherits from ScriptableObject, it should work.

I hope this helped!

I have never tried the BinaryFormatter with ScriptableObjects but based on how ScriptableObjects work it should not be possible to deserialize them. ScriptableObjects need to be created with the static CreateInstance method and must not be created with “new”. Since the BinaryFormatter only works with plain C# classes it always uses the constructor of the serialized classes when you deserialize them.

The deserialization might even work, but the actual ScriptableObjects wouldn’t be initialized correctly as their native C++ counter part would be missing and they would come up as “null”. If you want to use .NET serialization you shouldn’t derive your classes from ScriptableObject. If you need them to be ScriptableObjects you shouldn’t use .NET serialization.