TreeView
UnityEngine.UIElements.TreeView
Read time 3 minutesLast updated a month ago
Use TreeView to display hierarchical data in a tree-like structure. It's a powerful and flexible control that's commonly used to present data with parent-child relationships or nested structures.
If you need a simple list of items (not a hierarchical tree), consider using the ListView control.
Create a TreeView
You can create a TreeView with UI Builder, UXML, and C#. The following C# example creates a TreeView:
var treeView = new TreeView();
Refresh the collection view
In general, call the or method—these methods only refresh the collection view and are less expensive. If you call , the collection view is completely rebuilt, which can be expensive.
RefreshItemsRefreshItemRebuildHowever, you must call in the following cases:
Rebuild- You change the type of the data source, such as changing from a to a
List<float>.List<Vector3>
- You make changes to or
makeItem.destroyItem
Bind the TreeView to data
You can bind the TreeView to a data source. The data source can be a list of objects or a list of strings.
The following example binds a TreeView to a custom type.
treeView.makeItem = () => new VisualElement();var item = new VisualElement();treeView.bindItem = (item, i) =>{ var c = treeView.GetItemDataForIndex<MyCustomType>(i);};
Implement drag-and-drop operations for TreeView
Drag-and-drop is a common feature in UI design. To implement the drag-and-drop operations, override the following methods:
- To enable dragging items, override .
canStartDrag - To set which items are dragged, override .
setupDragAndDrop - To get item status changes, override . You can perform certain actions based on the drag position or other conditions.
dragAndDropUpdate - To control the drag-and-drop behavior, override .
handleDrop
During the drag-and-drop operation, you can enable the reordering of items by dragging. To enable, set the attribute to in UI Builder, UXML, and C#.
reorderabletrueRefer to Create a drag-and-drop list and tree views between windows for an example.
Set up the hierarchy of the TreeView
To set up the hierarchy of the TreeView, declare where is the type of data for the tree, then set the source through the API. For example, assume you have the following UXML structure:
TreeViewItemData<T>TSetRootItems<UXML xmlns="UnityEngine.UIElements"> <TreeView class="the-uxml-treeview" fixed-item-height="20" /></UXML>
The following USS example styles the TreeView:
.the-uxml-treeview { height: 200px;}.unity-tree-view__item-content > .unity-label { flex-grow: 1; margin-top: 2px;}
You can set up the hierarchy of the TreeView as follows:
var treeView = container.Q<TreeView>(); // Create some list of data, here simply numbers in a few foldouts var items = new List<TreeViewItemData<string>>(10); for (var i = 0; i < 10; i++) { var itemIndex = i * 10 + i; var treeViewSubItemsData = new List<TreeViewItemData<string>>(10); for (var j = 0; j < 10; j++) treeViewSubItemsData.Add(new TreeViewItemData<string>(itemIndex + j + 1, $"Data {i+1}-{j+1}")); var treeViewItemData = new TreeViewItemData<string>(itemIndex, $"Data {i+1}", treeViewSubItemsData); items.Add(treeViewItemData); }; // The "makeItem" function will be called as needed // when the TreeView needs more items to render Func<VisualElement> makeItem = () => new Label(); // As the user scrolls through the list, the TreeView object // will recycle elements created by the "makeItem" // and invoke the "bindItem" callback to associate // the element with the matching data item (specified as an index in the list) Action<VisualElement, int> bindItem = (e, i) => { var item = treeView.GetItemDataForIndex<string>(i); var id = treeView.GetIdForIndex(i); ((Label)e).text = $"ID {id} - {item}"; }; treeView.SetRootItems(items); treeView.makeItem = makeItem; treeView.bindItem = bindItem; treeView.selectionType = SelectionType.Multiple; treeView.Rebuild(); // Callback invoked when the user double clicks an item treeView.itemsChosen += (selectedItems) => { Debug.Log("Items chosen: " + string.Join(", ", selectedItems)); }; // Callback invoked when the user changes the selection inside the TreeView treeView.selectedIndicesChanged += (selectedIndices) => { var log = "IDs selected: "; foreach (var index in selectedIndices) { log += $"{treeView.GetIdForIndex(index)}, "; } Debug.Log(log.TrimEnd(',', ' ')); };
To try this example live in Unity, go to Window > UI Toolkit > Samples.
TreeView FAQs
The following are some frequently asked questions about the TreeView control:
Can I get the list of rows that are visible in the view?
There are no dedicated APIs for this. You can use UQuery to retrieve the elements of interest.
Is it mandatory for any of the overridden functions of a view controller to call ?
base.MethodCall this method only if you want to extend its default behavior.
I’ve added a Toggle to my row. Why doesn’t the selection jump to that row when the user selects it?
By default, the row is selected only if the mouse down event is not consumed by the row's contents. In this case, your Toggle stops the event propagation. To fix this, register a callback with on the Toggle to call .
PointerDownEventTrickleDownSetSelectionHow do I receive a callback when a user changes their selection in the view?
It is recommended to use the callback to retrieve data by index when needed. While you can also use , be aware that it returns a list of objects, which can cause boxing allocations when used with value types.
selectedIndicesChangedselectionChangedCan I get the indices of the rows that are visible on the screen?
There are no dedicated APIs for this. You can use the and callbacks to track these indices in .
bindItemunbindItemuserDataHow do I convert from ID to index and vice versa?
Can I have a horizontal TreeView?
The TreeView control doesn't support horizontal layout and virtualization. It's recommended to use a ScrollView with to layout elements horizontally.
flex-direction: rowExamples
- Create list and tree views: Use ListView, TreeView, MultiColumnListView, and MultiColumnTreeView to create list and tree views.
- Create a drag-and-drop list and tree views between windows: Use ListView, TreeView, and MultiColumnListView to create a drag-and-drop UI between windows.
C# base class and namespace
C# class:
TreeViewNamespace:
UnityEngine.UIElementsBase class:
BaseTreeViewMember UXML attributes
This element has the following member attributes:
Name | Type | Description |
|---|---|---|
| | A UXML template that constructs each recycled and rebound element within the tree. This template is designed to replace the |
Inherited UXML attributes
This element inherits the following attributes from its base class:
Name | Type | Description |
|---|---|---|
| | When true, items are automatically expanded when added to the TreeView. |
| | Path of the target property to be bound. |
| | The height of a single item in the list, in pixels. This property must be set when using the |
| | If false, this prevents the element from being focused. The element can only be focused if its canGrabFocus property is true. |
| | This property controls whether the collection view shows a horizontal scroll bar when its content does not fit in the visible area. |
| | Gets or sets a value that indicates whether the user can drag list items to reorder them. The default value is |
| | Controls the selection type. The default value is |
| | This property controls whether the background colors of collection view rows alternate. Takes a value from the |
| | Enable this property to display a border around the collection view. If set to true, a border appears around the ScrollView that the collection view uses internally. |
| | An integer used to sort focusable elements in the focus ring. Must be greater than or equal to zero. Setting the |
| | The virtualization method to use for this collection when a scroll bar is visible. Takes a value from the The default value is |
This element also inherits the following attributes from :
VisualElementName | Type | Description |
|---|---|---|
| | Logical container where child elements are added. If a child is added to this element, the child is added to this element's content container instead. When iterating over the If the content container is the same as the element itself, child elements are added directly to the element. This is true for most elements but can be overridden by more complex types. The |
| | Assigns a data source to this VisualElement which overrides any inherited data source. This data source is inherited by all children. |
| | Path from the data source to the value. |
| | The possible type of data source assignable to this VisualElement. This information is only used by the UI Builder as a hint to provide some completion to the data source path field when the effective data source cannot be specified at design time. |
| | Returns true if the This flag isn't changed if the VisualElement is disabled implicitly by one of its parents. To verify this, use |
| | Indicates the directionality of the element's text. The value will propagate to the element's children. Setting |
| | The name of this VisualElement. Use this property to write USS selectors that target a specific element. The standard practice is to give an element a unique name. |
| | Determines if this element can be the target of pointer events or picked by Elements can not be picked if: - They are invisible- Their Elements with a picking mode of |
| | Sets the style values on a The returned style data, computed from USS files or inline styles written to this object in C#, doesn't represent the fully resolved styles, such as the final height and width of a VisualElement. To access these fully resolved styles, use For information about how to use this property and all the supported USS properties, refer to the Apply styles in C# scripts and USS properties reference manual pages. |
| | Text to display inside an information box after the user hovers the element for a small amount of time. This is only supported in the Editor UI. |
| | A combination of hint values that specify high-level intended usage patterns for the |
| | Used for view data persistence, such as tree expanded states, scroll position, or zoom level. This key is used to save and load the view data from the view data store. If you don't set this key, the persistence is disabled for the associated |
USS classes
The following table lists all the C# public property names and their related USS selector.
C# property | USS selector | Description |
|---|---|---|
| | The USS class name for TreeView elements. Unity adds this USS class to every instance of the TreeView element. Any styling applied to this class affects every TreeView located beside, or below the stylesheet in the visual tree. |
| | The USS class name for TreeView item elements. Unity adds this USS class to every item element of the TreeView. Any styling applied to this class affects every item located beside, or below the stylesheet in the visual tree. |
| | The USS class name for TreeView item toggle elements. Unity adds this USS class to every item toggle element of the TreeView. Any styling applied to this class affects every item located beside, or below the stylesheet in the visual tree. |
| | The USS class name for TreeView indent container elements. Unity adds this USS class to every indent container element of the TreeView. Any styling applied to this class affects every item located beside, or below the stylesheet in the visual tree. |
| | The USS class name for TreeView indent element. Unity adds this USS class to every indent element of the TreeView. Any styling applied to this class affects every item located beside, or below the stylesheet in the visual tree. |
| | The USS class name for TreeView item container elements. Unity adds this USS class to every item container element of the TreeView. Any styling applied to this class affects every item located beside, or below the stylesheet in the visual tree. |
| | The USS class name for BaseVerticalCollectionView elements. Unity adds this USS class to every instance of the BaseVerticalCollectionView element. Any styling applied to this class affects every BaseVerticalCollectionView located beside, or below the stylesheet in the visual tree. |
| | The USS class name for BaseVerticalCollectionView elements with a border. Unity adds this USS class to an instance of the BaseVerticalCollectionView element if the instance's |
| | The USS class name of item elements in BaseVerticalCollectionView elements. Unity adds this USS class to every item element the BaseVerticalCollectionView contains. Any styling applied to this class affects every item element located beside, or below the stylesheet in the visual tree. |
| | The USS class name of the drag hover bar. Unity adds this USS class to the bar that appears when the user drags an item in the list. Any styling applied to this class affects every BaseVerticalCollectionView located beside, or below the stylesheet in the visual tree. |
| | The USS class name of the drag hover circular marker used to indicate depth. Unity adds this USS class to the bar that appears when the user drags an item in the list. Any styling applied to this class affects every BaseVerticalCollectionView located beside, or below the stylesheet in the visual tree. |
| | The USS class name applied to an item element on drag hover. Unity adds this USS class to the item element when it's being dragged. Any styling applied to this class affects every BaseVerticalCollectionView item located beside, or below the stylesheet in the visual tree. |
| | The USS class name of selected item elements in the BaseVerticalCollectionView. Unity adds this USS class to every selected element in the BaseVerticalCollectionView. The |
| | The USS class name for odd rows in the BaseVerticalCollectionView. Unity adds this USS class to every odd-numbered item in the BaseVerticalCollectionView when the |
| | The USS class name of the scroll view in the BaseVerticalCollectionView. Unity adds this USS class to the BaseVerticalCollectionView's scroll view. Any styling applied to this class affects every BaseVerticalCollectionView scroll view located beside, or below the stylesheet in the visual tree. |
| | USS class name of local disabled elements. |
You can also use the Matching Selectors section in the Inspector or the UI Toolkit Debugger to see which USS selectors affect the components of the at every level of its hierarchy.
VisualElement