Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

SerializedProperty of Generics

Discussion in '2020.1 Beta' started by Araj, Jul 1, 2020.

  1. Araj

    Araj

    Joined:
    Jan 3, 2013
    Posts:
    27
    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:
    Code (CSharp):
    1. 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:
    Code (CSharp):
    1. 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):
    Code (CSharp):
    1. [Serializable]
    2.     public class GenericDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ISerializationCallbackReceiver
    3. {
    4.         [SerializeField] List<TKey> keys = new List<TKey>();
    5.         [SerializeField] List<TValue> values = new List<TValue>();
    6.         ...
    7.         ...
    8.         ...
    9. }
    And this is the code that creates the VisualElements to render the dictionary.
    Code (CSharp):
    1. public static VisualElement CreateDictionary(SerializedProperty property, PropertyDrawer drawer)
    2.         {
    3.             if (property != null)
    4.             {
    5.                 var keys = property.FindPropertyRelative("keys");
    6.                 var values = property.FindPropertyRelative("values"); // This returns null if the "values" property is a List.
    7.                 if (keys != null && values != null)
    8.                 {
    9.                     ...
    10.                 }
    11.                 ...
    12.             }
    13.             ...
    14. }
    The "property.FindPropertyRelative" part returns null if the keys or values are Lists or Arrays.

    Do you know how could I fix that?
     
  2. daniel_lochner

    daniel_lochner

    Joined:
    Jun 9, 2016
    Posts:
    163
    Hi there Araj, did you ever figure out the issue?