- Home /
How to serialize a Dictionary?
I'm trying to modify the TagFrenzy plugin to use a dictionary instead of a list for the tags. The issue I'm running into is that the Dictionary is not being found when I try and use mySerializedDictionary = tagger.FindProperty("MyDictionary");
If I replace "MyDictioanry" with a list of the same name it is found.
Is this possible in unity?
Not sure if you can directly serialize this type of object... but... have you tried to create a wrapper class that Inherits from the dictionary and serialize that one? It helped me out before when serializing complex objects to xml.
Pretty much I'm trying to modify TagFrenzy so that when you select a tag from the inspector it modifies a dictionary ins$$anonymous$$d of a list. So that I can do lookups via key, ins$$anonymous$$d of iterating through the list of tags.
... or use Linq to found your item directly ins$$anonymous$$d of iterating
I'm concerned about performance, the last thing I want to use in this situation is LINQ. I'm using multiple tags as a simpler way than type-checking to identify objects that are within a spherical collider of another object. (when you have a few hundred objects all within each others "range" the number of checks for each collider to deter$$anonymous$$e friend from foe, inanimate from animate, shoot this don't shoot that...etc Rises dramatically)
Answer by apple92 · May 31, 2015 at 08:50 AM
Serialization of Dictonaries isn't directly possible in Unity... BUT..
You can use the ISerializationCallbackReceiver. If you additionaly add CallbackReceiver to derive from (Instead of only MonoBehaviour, or something else), you can make changes before and after serialization. Like this you can run through your Dictonary and split it into two List in OnBeforeSerialization(). Lists can nativly be serialized with Unity. OnAfterDeserialize() you would iterate through the Lists and recreate your Dictonary.
Link to the Full explanation:
Like this, your Dictonary should no longer become empty everytime an Assembly gets reloaded, etc.
Regards Michael