Search code examples
c#unity-game-engineui-toolkit

How to add an array of gameObjects to an Editor window in the new Unity UI ToolKit?


I can't find how to add an array of gameObjects to an Editor window in the new Unity UI ToolKit like in the picture:

enter image description here

I don't find an array component in the UI Builder library and the ListView does not seem to be the right choice for me.


Solution

  • I'm not very familiar with the "new" UIToolkit (still not getting warm with it ^^) but this seems to work for me

    public class TEstEditorWindow : EditorWindow
    {
        private List<GameObject> prefabs;
        private ListView list;
    
        [MenuItem("TEEST/Testitest")]
        public static void Open()
        {
            var window = GetWindow<TEstEditorWindow>();
            window.Show();
        }
    
        private void CreateGUI()
        {
            DrawReorderableList(prefabs, rootVisualElement);
        }
    
        // jut making this static so it can be generalized and used everywhere
        public static void DrawReorderableList<T>(List<T> sourceList, VisualElement rootVisualElement, bool allowSceneObjects = true) where T : UnityEngine.Object
        {
            var list = new ListView(sourceList)
            {
                virtualizationMethod = CollectionVirtualizationMethod.DynamicHeight,
                showFoldoutHeader = true,
                headerTitle = "Prefabs",
                showAddRemoveFooter = true,
                reorderMode = ListViewReorderMode.Animated,
                makeItem = () => new ObjectField
                {
                    objectType = typeof(T),
                    allowSceneObjects = allowSceneObjects
                },
                bindItem = (element, i) =>
                {
                    ((ObjectField)element).value = sourceList[i];
                    ((ObjectField)element).RegisterValueChangedCallback((value) =>
                    {
                        sourceList[i] = (T)value.newValue;
                    });
                }
            };
    
            rootVisualElement.Add(list);
        }
    }
    

    I sure hope there is a better an more stable way to do this though ^^

    enter image description here

    See also