Search code examples
c#unity-game-engineunity-editor

How to make ReorderableList elements expand and resize correctly in inspector?


I have a list of objects that I display in the editor using a CustomPropertyDrawer currently I store that list using a ReorderableList, for which I have overriden drawElementCallback and onAddDropdownCallback, the relevant code looks like this:

        reorderableList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) =>
        {
            GUIContent elementLabel = new GUIContent();
            elementLabel.text = "element " + index;
            Rect elementRect = new Rect(rect.x, rect.y, rect.width, EditorGUI.GetPropertyHeight(list.GetArrayElementAtIndex(index)));
                
            EditorGUI.indentLevel++;
            EditorGUI.PropertyField(elementRect, list.GetArrayElementAtIndex(index), elementLabel, true);
            EditorGUI.indentLevel--;
        };

My problem is the following: The elements of the list don't expand the correct way, when expanded, they occupy space that they are not supposed to, like these examples. First element expanded Last element expanded The dark grey space under the list DOES expand, so somewhere the property knows that it should take more space... but somehow that space is not utilized by the list elements.

I'd like the next elements to shift down to make room for the expanded one, and to make the light grey field of the list grow to accomodate.

Potentialy important note: the items of my list all have a common class that they inherit from, but they are not the same type as eachother necessarily, so they won't all have the same height (like in my two images, the elements are different types).

I think My error is somewhere in the provided function... I thought calling GetPropertyHeight() on the elements would return a greater height if the element is expanded, but it appears that is not the case, should I even use a ReorderableList here?

Edit: I have tried using EditorGUILayout.PropertyField() instead of EditorGUI.PropertyField() to get the list items height automaticaly, I get this result, which behaves closer to my excpectations, although the list itself is now shifted down from the light-grey area... Inspector when using EditorGUILayout


Solution

  • You will have to properly implement reorderableList.elementHeightCallback.

    reorderableList.drawElementCallback = index =>
    {
        SerializedProperty element = reorderableList.serializedProperty.GetArrayElementAtIndex(index);
    
        // for example this or whatever you want/have to do custom
        return EditorGUI.GetPropertyHeight(element);
    };
    

    And no, within the ReorderableList callbacks implementations you have to use the EditorGUI type with fixed Rect drawing and cannot use the auto layouted EditorGUILayout type.

    This basically behaves the same way as a Custom PropertyDrawer using GetPropertyHeight for the height and OnGUI for the drawing itself