Hello I’m facing an issue with loading/saving data.
To keep track of player progression through my game, I created a Dictionary<EventFlags, bool> and I saved that using Newtonsoft.Json.
But I read it was better to use ScriptableObject instead of Enums (especially big ones) to avoid issues related to renaming, reordering etc.
My problem now though is that I can’t just save my Dictionary<EventFlagsObj, bool> anymore. Because I get the error:
An error occured when trying to load data from file: path/to/my/save.json
Newtonsoft.Json.JsonSerializationException: Could not convert string ‘So_CanGoToSoleanna (SonicEventFlagsObj)’ to dictionary key type ‘EventFlagsObj’. Create a TypeConverter to convert from the string to the key type object. Path ‘episodes.Sonic.eventFlags[‘So_CanGoToSoleanna (SonicEventFlagsObj)’]’, line 396, position 50. —> Newtonsoft.Json.JsonSerializationException: Error converting value “So_CanGoToSoleanna (SonicEventFlagsObj)” to type ‘EventFlagsObj’. Path ‘episodes.Sonic.eventFlags[‘So_CanGoToSoleanna (SonicEventFlagsObj)’]’, line 396, position 50. —> System.ArgumentException: Could not cast or convert from System.String to EventFlagsObj.
SonicEventFlagsObj inherit from EventFlagsObj btw
Can someone help ?
Thank you.
EDIT: I’m not sure how that would work anyway because how could the references be the same…
I’ve told you this before, you can’t serialise Unity objects or references to them to disk and deserialise them later.
You have to use non-Unity objects, or use an identifier instead and restore the reference after loading (or during deserialisation if the serialiser has an API to support that), or use an indirect reference instead.
When loading, you can never re-create a MonoBehaviour or ScriptableObject instance directly from JSON. Save data needs to be all entirely plain C# data with no Unity objects in it.
Loading/Saving ScriptableObjects by a proxy identifier such as name:
This does require an engineering decision of how you will identify things. I suggest keeping it simple and having 100% unique names, never renaming them, as noted in the above post. Yes you can do more whacky things in the future, but get the above working first, then go nuts later.