unity-game-engineunity-editorreorderable-list

Unity - Reorderable List is never focused or selected


I have a custom Editor where I use a Reorderable List. Its elements are never focused nor selected whether I use a custom method or the default ones. Here's my code:

public class CustomClass : ScriptableObject
{
    [SerializeFied] List<int> _startingElements = new List<int>();
}

[CustomEditor(typeof(CustomClass), true)]
    ReorderableList _reorderableStartingElements;

public override void OnInspectorGUI()
{          
    GUIStyle HeaderBackground = new GUIStyle("RL Header");

    Rect position = EditorGUILayout.GetControlRect(false, 7.5f);
    position.height = EditorGUIUtility.singleLineHeight;

    _reorderableStartingElements = new ReorderableList(serializedObject, serializedObject.FindProperty("_startingElements"), true, true, true, true)
    {
         drawElementBackgroundCallback = DrawListElementBackground,
         elementHeight = 19,
         elementHeightCallback = CalculateCallHeight
    };

    _reorderableStartingElements.DoLayoutList();

    serializedObject.ApplyModifiedProperties();
}
      
private float CalculateCallHeight(int index)
{
    return EditorGUI.GetPropertyHeight(_reorderableStartingElements.serializedProperty.GetArrayElementAtIndex(index));
}

public void DrawListElementBackground(Rect rect, int index, bool selected, bool focused)
{
    if (Event.current.type != EventType.Repaint)
         return;

    GUIStyle HeaderBackground = new GUIStyle("RL Header");

    Color[] pix = new Color[Mathf.FloorToInt(rect.width * rect.height)];
          
    for (int i = 0; i < pix.Length; i++)
         pix[i] = selected || focused ? Color.blue : index % 2 == 0 ? Color.cyan : Color.yellow;
          
    Texture2D result = new Texture2D((int)rect.width, (int)5);
    result.SetPixels(pix);
    result.Apply();
          
    HeaderBackground.normal.background = result;
    EditorGUI.LabelField(rect, "", HeaderBackground);

    //ReorderableList.defaultBehaviours.elementBackground.Draw(rect, false, selected, selected, focused);
}

_startingElements is a simple List<int>. I left the comment where I use the default ReorderableList Draw method without succeess.

I know the code is not optimized, I'm just trying to make work it first.


Solution

  • Move the initialization to OnEnable, and use OnInspectorGUI to draw the list.

    private void OnEnable()
    {
        _reorderableStartingElements = new ReorderableList(serializedObject, serializedObject.FindProperty("_startingElements"), true, true, true, true)
        {
             drawElementBackgroundCallback = DrawListElementBackground,
             elementHeight = 19,
             elementHeightCallback = CalculateCallHeight
        };
    }
    private void OnInspectorGUI()
    {
        serializedObject.Update();
    
        _reorderableStartingElements.DoLayoutList();
    
        serializedObject.ApplyModifiedProperties();
    }