SerializedProperty of Generics

Hi!

Finally, it seems that we can create custom inspectors for generic classes in Unity 2020.1.

I’m trying to create a custom inspector with the UI Toolkit for a GenericDictionary<,>. So far, everything works beautifully. I can create dictionaries with:

GenericDictionary<string, int> dictionary = new GenericDictionary<string, int>();

And my custom editor renders it without issues.

The problem comes when I create a dictionary with a List or an array item as a Key or Value. For example, this:

GenericDictionary<string, List<int>> dictionary = new GenericDictionary<string, List<int>>();

Doesn’t work.

Unfortunately, I can’t share the full source of the Visual Element, as it’s owned by my company, but I can share the piece of the code that actually fails:

This is part of the GenericDictionary class (i’m just adding a few utility methods and the keys and value lists and that’s it):

[Serializable]
    public class GenericDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ISerializationCallbackReceiver
{
        [SerializeField] List<TKey> keys = new List<TKey>();
        [SerializeField] List<TValue> values = new List<TValue>();
        ...
        ...
        ...
}

And this is the code that creates the VisualElements to render the dictionary.

public static VisualElement CreateDictionary(SerializedProperty property, PropertyDrawer drawer)
        {
            if (property != null)
            {
                var keys = property.FindPropertyRelative("keys");
                var values = property.FindPropertyRelative("values"); // This returns null if the "values" property is a List.
                if (keys != null && values != null)
                {
                    ...
                }
                ...
            }
            ...
}

The “property.FindPropertyRelative” part returns null if the keys or values are Lists or Arrays.

Do you know how could I fix that?

3 Likes

Hi there Araj, did you ever figure out the issue?