Hi,
I’m trying to dynamically populate a list at runtime using ListView but nothing appears and MakeItem/BindItem aren’t being called. I’m creating/populating it in the constructor of a custom VisualElement and adding that to a .uxml file with a label above it.
public class RoomList : VisualElement
{
public new class UxmlFactory : UxmlFactory<RoomList, UxmlTraits> { }
public new class UxmlTraits : VisualElement.UxmlTraits { }
private ListView listView;
public RoomList()
{
IList items = Resources.LoadAll<RoomAsset>("Rooms");
listView = new ListView(items, 20, MakeItem, BindItem)
{
selectionType = SelectionType.Single,
horizontalScrollingEnabled = true
};
listView.style.flexGrow = 1f;
listView.style.flexShrink = 0f;
listView.style.flexBasis = 0f;
listView.onSelectionChange += Debug.Log;
Add(listView);
Debug.Log("RoomList constructor" + items.Count);
}
private void BindItem(VisualElement element, int index)
{
Debug.Log("RoomList BindItem");
var item = listView.itemsSource[index];
(element as TextElement).text = (item as RoomAsset).Name;
}
private VisualElement MakeItem()
{
Debug.Log("RoomList MakeItem");
//return new Label();
var ele = new TextElement();
ele.style.unityTextAlign = TextAnchor.MiddleLeft;
ele.style.paddingLeft = 5;
ele.style.flexGrow = 1f;
ele.style.flexShrink = 0f;
ele.style.flexBasis = 0f;
return ele;
}
}
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False">
<Style src="Room.uss" />
<ui:Label text="Rooms" display-tooltip-when-elided="true" style="font-size: 24px;" />
<RoomList name="RoomList" style="flex-direction: column;" />
</ui:UXML>
If put this in an editor window it does work:
void OnEnable()
{
IList items = Resources.LoadAll<RoomAsset>("Rooms");
listView = new ListView(items, 20, MakeItem, BindItem)
{
selectionType = SelectionType.Single,
horizontalScrollingEnabled = true
};
listView.style.flexGrow = 1f;
listView.style.flexShrink = 0f;
listView.style.flexBasis = 0f;
listView.onSelectionChange += Debug.Log;
rootVisualElement.Add(listView);
}
Is not possible to use this at runtime? Is there an alternative?
Cheers
Versions:
Unity 2021.1.0b12.2144.20
UI Toolkit 1.0.0-preview.14
UI Builder 1.0.0-preview.13