Version: 2022.3+
This example demonstrates how to create a list view runtime UI(User Interface) Allows a user to interact with your application. Unity currently supports three UI systems. More info
See in Glossary. This example uses the UXML and USS files directly to create the structure and style of the UI. If you are new to UI Toolkit and want to use UI Builder to create the UI, see Create an example UI with UI Builder.
This example creates a simple character selection screen. When you click the name of a character from a list on the left, the detail of the character appears on the right.
You can find the completed files that this example creates in this GitHub repository.
This guide is for developers familiar with the Unity Editor, UI Toolkit, and C# scripting. Before you start, get familiar with the following:
Create the main view UI Document and a USS file to style the visual elementsA node of a visual tree that instantiates or derives from the C# VisualElement
class. You can style the look, define the behaviour, and display it on screen as part of the UI. More info
See in Glossary. Add two visual elements as containers in the UI Document: one that contains the list of character names and another that contains the selected character’s details.
Create a project in Unity with any template.
In the Project windowA window that shows the contents of your Assets
folder (Project tab) More info
See in Glossary, create a folder named UI
to store all the UI Document and Style Sheet files.
In the UI
folder, create a UI Document named MainView.uxml
with the following content:
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False"> <Style src="MainView.uss" /> <ui:VisualElement name="background"> <ui:VisualElement name="main-container"> <ui:ListView focusable="true" name="character-list" /> <ui:VisualElement name="right-container"> <ui:VisualElement name="details-container"> <ui:VisualElement name="details"> <ui:VisualElement name="character-portrait" /> </ui:VisualElement> <ui:Label text="Label" name="character-name" /> <ui:Label text="Label" display-tooltip-when-elided="true" name="character-class" /> </ui:VisualElement> </ui:VisualElement> </ui:VisualElement> </ui:VisualElement> </ui:UXML>
In the UI
folder, create a USS style sheet named MainView.uss
with the following content:
#background { flex-grow: 1; align-items: center; justify-content: center; background-color: rgb(115, 37, 38); } #main-container { flex-direction: row; height: 350px; } #character-list { width: 230px; border-color: rgb(49, 26, 17); border-width: 4px; background-color: rgb(110, 57, 37); border-radius: 15px; margin-right: 6px; } #character-name { -unity-font-style: bold; font-size: 18px; } #character-class { margin-top: 2px; margin-bottom: 8px; padding-top: 0; padding-bottom: 0; } #right-container { justify-content: space-between; align-items: flex-end; } #details-container { align-items: center; background-color: rgb(170, 89, 57); border-width: 4px; border-color: rgb(49, 26, 17); border-radius: 15px; width: 252px; justify-content: center; padding: 8px; height: 163px; } #details { border-color: rgb(49, 26, 17); border-width: 2px; height: 120px; width: 120px; border-radius: 13px; padding: 4px; background-color: rgb(255, 133, 84); } #character-portrait { flex-grow: 1; -unity-background-scale-mode: scale-to-fit; } .unity-collection-view__item { justify-content: center; }
Create a UI Document and a Style Sheet for the individual entries in the list. The character list entry consists of a colored background frame and the character’s name.
In the UI
folder, create a UI Document named ListEntry.uxml
with the following content:
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False"> <Style src="ListEntry.uss" /> <ui:VisualElement name="list-entry"> <ui:Label text="Label" display-tooltip-when-elided="true" name="character-name" /> </ui:VisualElement> </ui:UXML>
In the UI
folder, create a Style Sheet file named ListEntry.uss
with the following content:
#list-entry { height: 41px; align-items: flex-start; justify-content: center; padding-left: 10px; background-color: rgb(170, 89, 57); border-color: rgb(49, 26, 17); border-width: 2px; border-radius: 15px; } #character-name { -unity-font-style: bold; font-size: 18px; color: rgb(49, 26, 17); }
Create sample data to fill the character list in the UI. For the character list, create a class that holds a character name, class, and a portrait image.
In the Asset folder, create a folder named Scripts
to store your C# scriptsA piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary.
In the Scripts
folder, create a C# script named CharacterData.cs
with the following content:
using UnityEngine; public enum ECharacterClass { Knight, Ranger, Wizard } [CreateAssetMenu] public class CharacterData : ScriptableObject { public string CharacterName; public ECharacterClass Class; public Sprite PortraitImage; }
This creates a Character Data item in the Assets > Create menu.
In the Assets folder, create a folder named Resources
.
In the Resources
folder, create a folder named Characters
to store all your sample character data.
In the Characters
folder, right-click and select Create > Character Data to create an instance of the ScriptableObject
.
Create more CharacterData
instances and fill them with placeholder data.
Create a UIDocument GameObjectThe fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info
See in Glossary in the SampleScene and add the UI Document as the source asset.
Create two C# scripts with the following classes:
CharacterListEntryController
class to display the data of a character instance in the UI of the list entry. It needs to access the label for the character name and set it to display the name of the given character instance.CharacterListController
class for the character list in the main view, and a MonoBehaviour
script that instantiates and assigns it to the visual treeAn object graph, made of lightweight nodes, that holds all the elements in a window or panel. It defines every UI you build with the UI Toolkit.
Note: The CharacterListEntryController
class isn’t a MonoBehaviour
. Since the visual elements in UI Toolkit aren’t GameObjects, you can’t attach components to them. Instead, you attach the class to the userData
property in the CharacterListController
class.
In the Scripts
folder, create a C# script named CharacterListEntryController.cs
with the following contents:
using UnityEngine.UIElements; public class CharacterListEntryController { Label m_NameLabel; // This function retrieves a reference to the // character name label inside the UI element. public void SetVisualElement(VisualElement visualElement) { m_NameLabel = visualElement.Q<Label>("character-name"); } // This function receives the character whose name this list // element is supposed to display. Since the elements list // in a `ListView` are pooled and reused, it's necessary to // have a `Set` function to change which character's data to display. public void SetCharacterData(CharacterData characterData) { m_NameLabel.text = characterData.CharacterName; } }
In the Scripts
folder, create a C# script named CharacterListController.cs
with the following content:
using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; public class CharacterListController { // UXML template for list entries VisualTreeAsset m_ListEntryTemplate; // UI element references ListView m_CharacterList; Label m_CharClassLabel; Label m_CharNameLabel; VisualElement m_CharPortrait; List<CharacterData> m_AllCharacters; public void InitializeCharacterList(VisualElement root, VisualTreeAsset listElementTemplate) { EnumerateAllCharacters(); // Store a reference to the template for the list entries m_ListEntryTemplate = listElementTemplate; // Store a reference to the character list element m_CharacterList = root.Q<ListView>("character-list"); // Store references to the selected character info elements m_CharClassLabel = root.Q<Label>("character-class"); m_CharNameLabel = root.Q<Label>("character-name"); m_CharPortrait = root.Q<VisualElement>("character-portrait"); FillCharacterList(); // Register to get a callback when an item is selected m_CharacterList.selectionChanged += OnCharacterSelected; } void EnumerateAllCharacters() { m_AllCharacters = new List<CharacterData>(); m_AllCharacters.AddRange(Resources.LoadAll<CharacterData>("Characters")); } void FillCharacterList() { // Set up a make item function for a list entry m_CharacterList.makeItem = () => { // Instantiate the UXML template for the entry var newListEntry = m_ListEntryTemplate.Instantiate(); // Instantiate a controller for the data var newListEntryLogic = new CharacterListEntryController(); // Assign the controller script to the visual element newListEntry.userData = newListEntryLogic; // Initialize the controller script newListEntryLogic.SetVisualElement(newListEntry); // Return the root of the instantiated visual tree return newListEntry; }; // Set up bind function for a specific list entry m_CharacterList.bindItem = (item, index) => { (item.userData as CharacterListEntryController)?.SetCharacterData(m_AllCharacters[index]); }; // Set a fixed item height matching the height of the item provided in makeItem. // For dynamic height, see the virtualizationMethod property. m_CharacterList.fixedItemHeight = 45; // Set the actual item's source list/array m_CharacterList.itemsSource = m_AllCharacters; } void OnCharacterSelected(IEnumerable<object> selectedItems) { // Get the currently selected item directly from the ListView var selectedCharacter = m_CharacterList.selectedItem as CharacterData; // Handle none-selection (Escape to deselect everything) if (selectedCharacter == null) { // Clear m_CharClassLabel.text = ""; m_CharNameLabel.text = ""; m_CharPortrait.style.backgroundImage = null; return; } // Fill in character details m_CharClassLabel.text = selectedCharacter.Class.ToString(); m_CharNameLabel.text = selectedCharacter.CharacterName; m_CharPortrait.style.backgroundImage = new StyleBackground(selectedCharacter.PortraitImage); } }
The CharacterListController
isn’t a MonoBehaviour
, so you can’t directly attach it to a GameObject. To overcome this, create a MonoBehaviour
script and attach it to the same GameObject as the UIDocument. In this script, you don’t need to instantiate the MainView.uxml
as it’s already instantiated by the UIDocument component. Instead, access the UIDocument component to get a reference of the already instantiated visual tree. Then, create an instance of the CharacterListController
and pass in the root element of the visual tree and the UXML template used for the individual list elements.
Note: When the UI reloads, any associated MonoBehaviour
components on the same GameObject that contain the UIDocument component are disabled before the reload, and then re-enabled after the reload. Therefore, you must place your UI-related code within the OnEnable
and OnDisable
methods of this MonoBehaviour
. For more information, refer to Render UI in the Game view.
In the Scripts
folder, create a C# script named MainView.cs
with the following content:
using UnityEngine; using UnityEngine.UIElements; public class MainView : MonoBehaviour { [SerializeField] VisualTreeAsset m_ListEntryTemplate; void OnEnable() { // The UXML is already instantiated by the UIDocument component var uiDocument = GetComponent<UIDocument>(); // Initialize the character list controller var characterListController = new CharacterListController(); characterListController.InitializeCharacterList(uiDocument.rootVisualElement, m_ListEntryTemplate); } }
In the SampleScene, select UIDocument.
Drag MainView.cs
to Add Component in the Inspector window.
Drag ListEntry.uxml to the ListEntry Template field.
Enter Play mode to see your UI displayed in the game view.
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.
When you visit any website, it may store or retrieve information on your browser, mostly in the form of cookies. This information might be about you, your preferences or your device and is mostly used to make the site work as you expect it to. The information does not usually directly identify you, but it can give you a more personalized web experience. Because we respect your right to privacy, you can choose not to allow some types of cookies. Click on the different category headings to find out more and change our default settings. However, blocking some types of cookies may impact your experience of the site and the services we are able to offer.
More information
These cookies enable the website to provide enhanced functionality and personalisation. They may be set by us or by third party providers whose services we have added to our pages. If you do not allow these cookies then some or all of these services may not function properly.
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us to know which pages are the most and least popular and see how visitors move around the site. All information these cookies collect is aggregated and therefore anonymous. If you do not allow these cookies we will not know when you have visited our site, and will not be able to monitor its performance.
These cookies may be set through our site by our advertising partners. They may be used by those companies to build a profile of your interests and show you relevant adverts on other sites. They do not store directly personal information, but are based on uniquely identifying your browser and internet device. If you do not allow these cookies, you will experience less targeted advertising. Some 3rd party video providers do not allow video views without targeting cookies. If you are experiencing difficulty viewing a video, you will need to set your cookie preferences for targeting to yes if you wish to view videos from these providers. Unity does not control this.
These cookies are necessary for the website to function and cannot be switched off in our systems. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms. You can set your browser to block or alert you about these cookies, but some parts of the site will not then work. These cookies do not store any personally identifiable information.