A good custom control is abstract, self-contained, and recurring.
A Slide Toggle is a good example of a custom control:
The menu bar of your application isn’t a good example of a custom control:
After you have created a custom control, you can style it with USS and add logic to handle events in C#.
To create a custom control, do the following:
UxmlElement
attribute to the custom control class definition.VisualElement
or one of its derived classes.For example:
using UnityEngine; using UnityEngine.UIElements; [UxmlElement] public partial class ExampleElement : VisualElement {}
You can use your custom controls in UXML and UI(User Interface) Allows a user to interact with your application. Unity currently supports three UI systems. More info
See in Glossary Builder after you create them.
The following example UXML document uses the custom control:
<ui:UXML xmlns:ui="UnityEngine.UIElements"> <ExampleElement /> </ui:UXML>
By default, the custom control appears in the Library tab in UI Builder. If you want to hide it from the Library tab, add the HideInInspector
attribute.
Custom controls inherit from VisualElement
. A VisualElement
isn’t bound to the lifetime of a 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 and doesn’t receive any of these callbacks:
Awake()
OnEnable()
OnDisable()
OnDestroy()
You can initialize a custom control in its constructor. However, if your application needs it, you can delay initialization until the custom control is added to the UI. To do this, register a callback for an AttachToPanelEvent
. To detect that your custom control has been removed from the UI, use the DetachFromPanelEvent
callback.
public CustomControl() { RegisterCallback<AttachToPanelEvent>(e => { /* do something here when element is added to UI */ }); RegisterCallback<DetachFromPanelEvent>(e => { /* do something here when element is removed from UI */ }); }
UI Toolkit dispatches these two events for all elements and doesn’t need a custom VisualElement
subclass. For more information, refer to Panel events.
Use USS to customize the look of a custom control the same way as a built-in control. You can also create USS custom properties to style a custom control.
Note: The InspectorA Unity window that displays information about the currently selected GameObject, asset or project settings, allowing you to inspect and edit the values. More info
See in Glossary window in the UI Builder doesn’t show USS custom properties. To edit USS custom properties, use a text editor to edit your USS file directly.
To interact with custom USS properties for a custom control in C#, use the CustomStyleProperty
structure and the CustomStylesResolvedEvent
event.
CustomStyleProperty
describes the name and type of property you read from the stylesheet.
UI Toolkit dispatches CustomStylesResolvedEvent
for any element that directly receives a custom USS property. It dispatches the event for any element that a selector matches, for selectors where the rule contains the value of the custom property. UI Toolkit doesn’t dispatch the event for elements that inherit the value. The event holds a reference to an ICustomStyle
object. You must use its TryGetValue()
method to read the effective value of a CustomStyleProperty
. This method has overloads for different types of CustomStyleProperty
.
For a custom style with a custom control example, refer to Create custom style for a custom control.
Note: You can’t define transitions for custom style properties.
For detailed information on how to handle events for custom controls, refer to Handle events.
Note:
focus
.Expose properties that a custom control represents and other functional aspects of its behavior as UXML properties, and expose properties that affect the look of a custom control as USS properties.
Use a namespace that’s unique, short, and readable to avoid name collisionsA collision occurs when the physics engine detects that the colliders of two GameObjects make contact or overlap, when at least one has a Rigidbody component and is in motion. More info
See in Glossary with other elements.
Keep UXML attributes primitive. Data that you can specify in UXML is limited to a set of primitive data types. UXML doesn’t support complex data structures or collections. Pass complex data to your custom controls at runtime via 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 or data binding, not in UXML.
In C#, expose USS classes or names as constants. This allows you to locate elements by class or name using UQuery.
Adopt the BEM standard for USS classes. This allows you to address every element with a class list selector.
Use static callbacks for a lower memory footprint. When you register an instance method to be used as a callback, you might create unnecessary allocations. To avoid allocations, use anonymous static lambda functions that call into regular C# static methods. You can retrieve the context of the current element through the EventBase.currentTarget
property.
Render custom geometry through the generateVisualContent
callback for custom controls. For an example usage that renders a partially filled circle, refer to the RadialProgress example.
Custom controls are convenient. However, you might achieve the same outcomes with the following:
MonoBehaviour
s to add logic that pertains to the specific UI Document that holds your UI. (To learn how to use MonoBehaviour
s to control UI in a UI Document, see Create your first runtime UI.) To achieve encapsulation, create properties and methods inside your MonoBehaviour
that internally fetch VisualElement
s with UQuery and manipulate their properties.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.