A PrefabAn asset type that allows you to store a GameObject complete with components and properties. The prefab acts as a template from which you can create new object instances in the scene. More info
See in Glossary is a pre-made 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 that you can instantiate multiple times in a sceneA Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info
See in Glossary. Prefabs are useful for creating reusable components. 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 in UI(User Interface) Allows a user to interact with your application. Unity currently supports three UI systems. More info
See in Glossary Toolkit aren’t GameObjects and therefore Prefabs don’t apply. However, you can create a custom control as a reusable UI component that encapsulates a specific hierarchy of elements with logic. Because UI Toolkit encourages you to separate the UI from your game or application code, you can use UXML to define the structure, use USS to define the look, and use C# to define the logic of your custom control.
As an example, let’s say you want to create a card game. You want to display cards with different statistics, such as life and attack.
You can create a custom control called CardElement
that displays the image, the life, and attack statistics for the character, and then reuse this custom control for each card in your game.
The following are the general steps to accomplish this:
In C#, declare a custom element type called CardElement.
In UXML, define the hierarchy of the custom control. You can use two approaches. Both approaches support instantiating the CardElement
in C# and in a parent UXML.
Locate references to child elements of the custom control.
Expose properties and methods, and encapsulate logic in your custom control the same way as you do with any C# classes.
Connect your custom control with your game or application code. You can also register event callbacks to implement user interaction.
With this approach, you include your custom element CardElement in the hierarchy UXML document and declare its child elements directly underneath, and use the hierarchy UXML document as a template. This approach offers a simpler solution with a fixed UI structure within the hierarchy UXML document.
The following C# and UXML examples demonstrate how to use the UXML-first approach to create reusable UI.
Create a C# script that defines CardElement custom control. The custom control class assigns an image and badge values to CardElement.
using UnityEngine; using UnityEngine.UIElements; // Define the custom control type. [UxmlElement] public partial class CardElement : VisualElement { private VisualElement portraitImage => this.Q("image"); private Label attackBadge => this.Q<Label>("attack-badge"); private Label healthBadge => this.Q<Label>("health-badge"); // Use the Init() approach instead of a constructor because // we don't have children yet. public void Init(Texture2D image, int health, int attack) { portraitImage.style.backgroundImage = image; attackBadge.text = health; healthBadge.text = attack; } // Custom controls need a default constructor. public CardElement() {} }
Create a UXML document (CardElement.uxml
) that defines the hierarchy of CardElement. This example styles CardElement with a USS file.
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False"> <Style src="CardElementUI.uss" /> <CardElement> <ui:VisualElement name="image" /> <ui:VisualElement name="stats"> <ui:Label name="attack-badge" class="badge" /> <ui:Label name="health-badge" class="badge" /> </ui:VisualElement> </CardElement> </ui:UXML>
You can connect your custom control to your game by the following:
CardElement.uxml
inside a parent UXML document. You can navigate back and forth between the hierarchy UXML and this UXML document in UI Builder.CardElement.uxml
containing CardElement
from a MonoBehaviour C# script. You must use UQuery to find CardElement before you add it to the scene.You call Init()
after adding the custom control into the scene.
You can also add gameplay-related actions, such as a click event to interact with the elements.
Instantiate inside parent UXML
The following shows an example of instantiation in UXML:
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False"> <ui:Template name="CardElement" src="CardElement.uxml"/> <ui:Instance template="CardElement"/> <ui:Instance template="CardElement"/> <ui:Instance template="CardElement"/> </ui:UXML>
For information on how to render the UXML document in your game, see Render UI in the Game view.
Instantiate directly in C#
Note: For learning purposes, the example code on this page uses the Resources folder method to load the UXML files which is convenient. However, this method doesn’t scale well. It’s recommended that you use other methods to load references for your production projects.
The following shows an example of instantiation in C#:
using UnityEngine; using UnityEngine.UIElements; public class UIManager : MonoBehaviour { public void Start() { UIDocument document = GetComponent<UIDocument>(); // Load the UXML document that defines the hierarchy of CardElement. // It assumes the UXML file is placed at the "Resources" folder. VisualTreeAsset template = Resources.Load<VisualTreeAsset>("CardElement"); // Create a loop to modify properties and perform interactions // for each card. It assumes that you have created a function // called `GetCards()` to get all the cards in your game. foreach(Card card in GetCards()) { // Instantiate a template container. var templateContainer = template.Instantiate(); // Find the custom element inside the template container. var cardElement = templateContainer.Q<CardElement>(); // Add the custom element into the scene. document.rootVisualElement.Add(cardElement); // Initialize the card. cardElement.Init(card.image, card.health, card.attack); // Register an event callback for additional interaction. cardElement.RegisterCallback<ClickEvent>(SomeInteraction); } } private void SomeInteraction(ClickEvent evt) { // Interact with the elements here. } }
With this approach, you only include the child elements in the hierarchy UXML document and use C# to load the hierarchy UXML document into the CardElement class definition. This approach offers a flexible UI structure for custom controls. For example, you can load different hierarchy UXML documents depending on specific conditions.
The following C# and UXML examples demonstrate how to use the element-first approach to create reusable UI.
Create a C# script that defines the CardElement custom control. In addition to defining a constructor to assign an image and badge values to CardElement, the custom control loads the hierarchy UXML document in its class definition.
using UnityEngine; using UnityEngine.UIElements; // Define the custom control type. [UxmlElement] public partial class CardElement : VisualElement { private VisualElement portraitImage => this.Q("image"); private Label attackBadge => this.Q<Label>("attack-badge"); private Label healthBadge => this.Q<Label>("health-badge"); // Custom controls need a default constructor. This default constructor // calls the other constructor in this class. public CardElement() {} // Define a constructor that loads the UXML document that defines // the hierarchy of CardElement and assigns an image and badge values. public CardElement(Texture2D image, int health, int attack) { // It assumes the UXML file is called "CardElement.uxml" and // is placed at the "Resources" folder. var asset = Resources.Load<VisualTreeAsset>("CardElement"); asset.CloneTree(this); portraitImage.style.backgroundImage = image; attackBadge.text = health.ToString(); healthBadge.text = attack.ToString(); } }
Note: If you have performance concerns, use lazy initialization to keep fields to cache the references and avoid re-evaluating the queries too often.
Create a UXML document (CardElement.uxml
) that defines the hierarchy of the child elements of CardElement. The example styles CardElement with a USS file.
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False"> <Style src="CardElementUI.uss" /> <ui:VisualElement name="image" /> <ui:VisualElement name="stats"> <ui:Label name="attack-badge" class="badge" /> <ui:Label name="health-badge" class="badge" /> </ui:VisualElement> </ui:UXML>
You can connect your custom control to your game by doing the following:
CardElement.uxml
inside a parent UXML document. In UI Builder, you can’t navigate back and forth between the hierarchy UXML and this UXML document because child elements are loaded from C#.CardElement.uxml
containing CardElement
from a MonoBehaviour C# script.You call the constructor before adding the custom control to the scene.
You can also add gameplay-related actions, such as a click event to interact with the elements.
Instantiate inside parent UXML
The following shows an example of instantiation in UXML:
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False"> <CardElement /> <CardElement /> <CardElement /> </ui:UXML>
For information on how to render the UXML document in your game, see Render UI in the Game view.
Instantiate directly in C#
The following shows an example of instantiation in C#:
using UnityEngine; using UnityEngine.UIElements; public class UIManager : MonoBehaviour { public void Start() { UIDocument document = GetComponent<UIDocument>(); // Create a loop to modify properties and perform interactions // for each card. It assumes that you have created a function // called `GetCards()` to get all the cards in your game. foreach(Card card in GetCards()) { var cardElement = new CardElement(card.image, card.health, card.attack); // Register an event callback for additional interaction. cardElement.RegisterCallback<ClickEvent>(SomeInteraction); // Add the custom element into the scene. document.rootVisualElement.Add(cardElement); } } private void SomeInteraction(ClickEvent evt) { // Interact with the elements here. } }
As the UI of your project gets more complex, it’s better to isolate your logic into higher-level components. This makes orchestrating the UI easier for the rest of the game or application.
You can apply the concepts on this page to gradually build specialized components out of smaller, more generic components. For example, to build a main title screen from which the user can access an Options menu and an About section, you can create a TitleScreenManager element with three different child UXML documents. Each defines its own elements: Title, Options, and About.
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.