概要
UIElements(UI Toolkit)でListViewを使ってReorderableListを作った際に子要素のバインドでつまづいたのでメモ。
バージョン : Unity 2022.1.24f1
コード
Runtime
using System;
using UnityEngine;
public sealed class Sample : MonoBehaviour
{
[SerializeField] private ListItem[] items;
}
[Serializable]
internal sealed class ListItem
{
public string name;
public Type type;
}
internal enum Type
{
None,
Normal,
Advanced
}
Editor
using UnityEditor;
using UnityEngine.UIElements;
[CustomEditor(typeof(Sample))]
public sealed class SampleEditor : UnityEditor.Editor
{
public override VisualElement CreateInspectorGUI()
{
var bodyElement = new VisualElement();
var listView = new ListView
{
bindingPath = "items",
reorderMode = ListViewReorderMode.Animated,
showAddRemoveFooter = true,
showBorder = true,
showFoldoutHeader = true,
headerTitle = "List Items",
virtualizationMethod = CollectionVirtualizationMethod.DynamicHeight,
makeItem = () =>
{
// 返すルートをBindableElementにしないと、子要素がバインドできないので注意
var root = new BindableElement { style = { flexDirection = FlexDirection.Row }};
var textField = new TextField { bindingPath = "name", style = { flexGrow = 1 } };
root.Add(textField);
var popupField = new EnumField {bindingPath = "type", style = {width = 120}};
root.Add(popupField);
return root;
}
};
bodyElement.Add(listView);
return bodyElement;
}
}