- 5.5.1p4
-
- (699250) - Scripting: Allow serialization of classes extending Dictionary.
it is mean we can serialization dictionary with json and prefab?
it is mean we can serialization dictionary with json and prefab?
Assuming it means you’re supposed to do this:
public class DictionarySerialized : MonoBehaviour {
[SerializeField]
public StringDict stringDict = new StringDict();
[Serializable]
public class StringDict : Dictionary<string, int>
{
}
}
Just tried it but couldn’t get it to work. The fields show up in the inspector, but without any way to specify contents. They don’t get saved into a scene file nor ScriptableObject. Doesn’t seem to work with JSON either, even when I add contents first at runtime. No changes to SerializedProperty to work with dictionaries either.
The only thing I can think this might do right now is have retain their contents when scripts are reloaded in the editor, like after a compile.
One problem with serializing dictionaries and saving them in a scene is that dictionaries don’t have a deterministic order, so the order of the dictionary entries may jump around. What I personally want is (a) serialization of generic parameters and (b) a dictionary data type that preserves insertion order that has all the bells and whistles. But that’s a lot of work.
Depends on how they’re serialized. Any json serializer that can handle Dictionaries should re-insert the values in the same order that it read them out, so the order should be deterministic in that regard.
I just meant that System.Collection.Generic.Dictionary<TKey, TValue> can’t be deterministic, because that class does not preserve insertion order.
There are tricks: You can declare a value array and key array in a subclass of Dictionary<TKey, TValue> then use ISerializationCallbackReceiver to compare the dictionary contents with the two arrays, trying to preserve the order (and also keep duplicate elements around so the inspector doesn’t get weird). That bloats your dictionaries a little, but the bigger problem we’ve had is that ISerializationCallbackReceiver is expensive and tanks editor performance when you use it a lot.
That’s what OrderedDictionary is for, in System.Collections.Specialized.
Not sure if Unity’s mono version has it but should, it’s been around since .NET 2.0.