class in UnityEngine.UIElements
/
Implemented in:UnityEngine.UIElementsModule
Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.
CloseFor some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.
CloseDeclares that a field or property is associated with nested UXML objects.
You can utilize the UxmlObjectReferenceAttribute to indicate that a property or field is
linked to one or multiple UXML objects.
By adding the UxmlObjectAttribute attribute to a class, you can declare a UXML object.
You can use these UXML objects to associate complex data with a field,
surpassing the capabilities of a single UxmlAttributeAttribute.
The field type must be a UXML object or an interface. When using an interface, only UXML Object types are valid for UXML serialization.
The following example shows a common use case for the UxmlObjectReferenceAttribute. It uses the attribute to associate a list of UXML objects with a field or property:
using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements;
[UxmlObject] public partial class Option { [UxmlAttribute] public string name { get; set; }
[UxmlAttribute] public bool bold { get; set; }
[UxmlAttribute] public Color color; }
[UxmlElement] public partial class MyColoredListField : VisualElement { private List<Option> m_Options; private PopupField<Option> m_PopupField;
[UxmlObjectReference("options")] public List<Option> options { get => m_Options; set { m_Options = value; m_PopupField.choices = m_Options; } }
public MyColoredListField() { m_PopupField = new PopupField<Option>(); Add(m_PopupField);
if (options != null) m_PopupField.choices = options;
m_PopupField.formatSelectedValueCallback = FormatItem; m_PopupField.formatListItemCallback = FormatItem; }
static string FormatItem(Option option) { if (option == null) return "";
var coloredString = $"<color=#{ColorUtility.ToHtmlStringRGB(option.color)}>{option.name}</color>";
if (option.bold) return $"<b>{coloredString}</b>"; return coloredString; } }
Example UXML:
<ui:UXML xmlns:ui="UnityEngine.UIElements"> <MyColoredListField> <options> <Option name="Red" color="#FF0000FF" bold="true" /> <Option name="Green" color="#00FF00FF" /> <Option name="Blue" color="#0000FFFF" /> </options> </MyColoredListField> </ui:UXML>
You can employ a base type and incorporate derived types as UXML objects. The following example customizes a button to exhibit different behaviors when clicked, such as displaying a label or playing a sound effect.
using UnityEngine; using UnityEngine.UIElements;
[UxmlObject] public abstract partial class ButtonBehaviour { [UxmlAttribute] public string name { get; set; }
public abstract void OnClicked(Button button); }
[UxmlObject] public partial class CreateLabel : ButtonBehaviour { [UxmlAttribute] public string text { get; set; } = "I was clicked!";
public override void OnClicked(Button button) { var label = new Label(text); button.parent.Add(label); } }
[UxmlObject] public partial class PlaySound : ButtonBehaviour { [UxmlAttribute] public AudioClip sound { get; set; }
public override void OnClicked(Button button) { AudioSource.PlayClipAtPoint(sound, Vector3.zero); } }
[UxmlElement] public partial class ButtonWithClickBehaviourExample : Button { [UxmlObjectReference("clicked")] public ButtonBehaviour clickedBehaviour { get; set; }
public ButtonWithClickBehaviourExample() { clicked += OnClick; }
void OnClick() { clickedBehaviour?.OnClicked(this); } }
Example UXML:
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False"> <ButtonWithClickBehaviourExample text="Play Sound"> <clicked> <PlaySound sound="project://database/Assets/ClickedSound.wav" /> </clicked> </ButtonWithClickBehaviourExample> <ButtonWithClickBehaviourExample text="Show Label"> <clicked> <CreateLabel text="I was clicked!" /> </clicked> </ButtonWithClickBehaviourExample> </ui:UXML>
You can also use an interface with UXML objects that implement it.
using System.Collections.Generic; using UnityEngine.UIElements;
public interface IMyUxmlObjectInterface { string name { get; set; } }
[UxmlObject] public partial class MyUxmlObject : IMyUxmlObjectInterface { [UxmlAttribute] public string name { get; set; } }
[UxmlElement] public partial class MyUxmlObjectElement : VisualElement { [UxmlObjectReference("item")] public IMyUxmlObjectInterface item { get; set; }
[UxmlObjectReference("item-list")] public List<IMyUxmlObjectInterface> itemList { get; set; } }
The following example creates multiple UxmlObjects types with custom property drawers. It uses UxmlObjects to describe schools, teachers, and students:
using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements;
/// <summary> /// The classes that a student can take. /// </summary> public enum Class { Maths, MathsAdvanced, Science, ScienceAdvanced, Psychology, Sociology, Economics, English, French, History, }
/// <summary> /// The base class contains the common properties for both students and teachers. /// </summary> [UxmlObject] public abstract partial class Person { [UxmlAttribute] public int Id { get; set; }
[UxmlAttribute] public string Name { get; set; } }
/// <summary> /// A student has a list of classes and a photo. /// </summary> [UxmlObject] public partial class Student : Person { [UxmlAttribute] public List<Class> Classes { get; set; }
[UxmlAttribute] public Texture2D Photo { get; set; } }
/// <summary> /// A teacher has a list of classes taught. /// </summary> [UxmlObject] public partial class Teacher : Person { [UxmlAttribute] public List<Class> ClassesTaught { get; set; } }
/// <summary> /// A school has a list of people which includes both students and teachers. /// </summary> [UxmlObject] public partial class School { [UxmlAttribute] public string Name { get; set; }
[UxmlAttribute] public int NextAvailableId;
[UxmlObjectReference("people")] public List<Person> People { get; set; } }
/// <summary> /// A school district has a list of schools. /// </summary> [UxmlElement] public partial class SchoolDistrict : VisualElement { [UxmlObjectReference("schools")] public List<School> Schools { get; set; } }
You can use a custom property drawer to display the UXML objects in the Inspector. The property drawer must be for the UxmlObject's UxmlSerializedData type. For example, to create a property drawer for the UxmlObject Student, the drawer must be for the type Studen.UxmlSerializedData.
using UnityEditor; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.UIElements;
// Note: The custom property drawer must be for the serialized data type. [CustomPropertyDrawer(typeof(School.UxmlSerializedData))] public class SchoolPropertyDrawer : PropertyDrawer { SerializedProperty m_People; SerializedProperty m_NextAvailableId; ListView m_ListView;
int GetNextId() { var id = m_NextAvailableId.intValue; if (id == 0) id++;
m_NextAvailableId.intValue = id + 1; return id; }
public override VisualElement CreatePropertyGUI(SerializedProperty property) { var root = new VisualElement();
m_People = property.FindPropertyRelative("People"); m_NextAvailableId = property.FindPropertyRelative("NextAvailableId");
var name = new PropertyField(); name.BindProperty(property.FindPropertyRelative("Name")); root.Add(name);
m_ListView = new ListView { showAddRemoveFooter = true, showBorder = true, showBoundCollectionSize = false, showAlternatingRowBackgrounds = AlternatingRowBackground.All, overridingAddButtonBehavior = OnAddItem, reorderable = true, reorderMode = ListViewReorderMode.Animated, virtualizationMethod = CollectionVirtualizationMethod.DynamicHeight, bindingPath = m_People.propertyPath, };
root.Add(m_ListView);
return root; }
void OnAddItem(BaseListView baseListView, Button button) { var menu = new GenericMenu(); menu.AddItem(new GUIContent("Student"), false, () => AddItem<Student>()); menu.AddItem(new GUIContent("Teacher"), false, () => AddItem<Teacher>()); menu.DropDown(button.worldBound); }
void AddItem<T>() where T : new() { m_People.InsertArrayElementAtIndex(m_People.arraySize); var person = m_People.GetArrayElementAtIndex(m_People.arraySize - 1); person.managedReferenceValue = UxmlSerializedDataCreator.CreateUxmlSerializedData(typeof(T)); person.FindPropertyRelative("Id").intValue = GetNextId(); m_People.serializedObject.ApplyModifiedProperties(); m_ListView.RefreshItem(m_People.arraySize - 1); } }
[CustomPropertyDrawer(typeof(Student.UxmlSerializedData))] public class StudentPropertyDrawer : PropertyDrawer { public override VisualElement CreatePropertyGUI(SerializedProperty property) { var id = property.FindPropertyRelative("Id").intValue; var photo = property.FindPropertyRelative("Photo").objectReferenceValue as Texture2D;
var root = new VisualElement { style = { backgroundColor = new Color(0, 0.2f, 0, 0.25f) } }; root.Add(new Label($"Student({id})") { style = { unityTextAlign = TextAnchor.MiddleCenter } }); var image = new Image { image = photo, style = { height = 100, width = 100 } }; root.Add(image);
var name = new PropertyField(); name.BindProperty(property.FindPropertyRelative("Name")); root.Add(name);
var photoField = new PropertyField(); photoField.BindProperty(property.FindPropertyRelative("Photo")); photoField.RegisterValueChangeCallback(evt => { image.image = property.FindPropertyRelative("Photo").objectReferenceValue as Texture2D; }); root.Add(photoField);
var course = new PropertyField(); course.BindProperty(property.FindPropertyRelative("Classes")); root.Add(course);
return root; } }
[CustomPropertyDrawer(typeof(Teacher.UxmlSerializedData))] public class TeacherPropertyDrawer : StudentPropertyDrawer { public override VisualElement CreatePropertyGUI(SerializedProperty property) { var id = property.FindPropertyRelative("Id").intValue; var root = new VisualElement { style = { backgroundColor = new Color(0, 0, 0.2f, 0.25f) } }; root.Add(new Label($"Teacher({id})") { style = {unityTextAlign = TextAnchor.MiddleCenter }});
var name = new PropertyField(); name.BindProperty(property.FindPropertyRelative("Name")); root.Add(name);
var classField = new PropertyField(); classField.BindProperty(property.FindPropertyRelative("ClassesTaught")); root.Add(classField);
return root; } }
Example UXML:
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" editor-extension-mode="False"> <SchoolDistrict> <schools> <School name="Herrington High School" next-available-id="6"> <people> <Teacher id="1" classes-taught="Science" name="Elizabeth Burke" /> <Teacher id="2" classes-taught="Maths" name="Coach Willis" /> <Student id="3" classes="Maths" name="Casey Connor" /> <Student id="4" classes="Maths,English,French,History,Sociology" name="Delilah Profitt" /> <Student id="5" classes="Maths,MathsAdvanced,Science,ScienceAdvanced" name=" Marybeth Louise Hutchinson" /> </people> </School> <School name="Shermer High School" next-available-id="9"> <people> <Teacher id="3" classes-taught="English" name="Ed Rooney" /> <Teacher id="4" name="Mr. Lorensax" classes-taught="Economics" /> <Teacher id="5" classes-taught="English" name="Mr. Knowlan" /> <Teacher id="6" classes-taught="History" name="Mr. Rickets" /> <Student id="1" classes="Maths,Science,English" name="Ferris Bueller" /> <Student id="7" classes="Maths,MathsAdvanced,Science,ScienceAdvanced,French" name="Cameron Frye" /> <Student id="8" classes="Sociology,Economics,Phycology" name="Sloan Peterson" /> </people> </School> <School name="Sunnydale High School" next-available-id="6"> <people> <Teacher id="1" classes-taught="Science,ScienceAdvanced" name="Grace Newman" /> <Teacher id="2" classes-taught="Science" name="Dr. Gregory" /> <Student id="3" classes="Maths" name=" James Stanley" photo="project://database/Assets/james-class-photo.jpg" /> <Student id="4" classes="Maths,English,French,History,Sociology" name="Buffy Summers" photo="project://database/Assets/buffy-class-photo.jpg" /> <Student id="5" classes="Maths,MathsAdvanced,Science,ScienceAdvanced" name="Willow Rosenberg" photo="project://database/Assets/willow-class-photo.jpg" /> </people> </School> </schools> </SchoolDistrict> </ui:UXML>
name | The name of the nested UXML element that the UXML Objects are serialized to. Note: A null or empty value will result in the objects being serialized into the root. |
types | In UI Builder, when adding a UXML Object to a field that has multiple derived types, a dropdown list appears with a selection of available types that can be added to the field. By default, this list comprises all types that inherit from the UXML object type. You can use a parameter to specify a list of accepted types to be displayed, rather than showing all available types |
UxmlObjectReferenceAttribute | Declares that a field or property is associated with nested UXML objects. |
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.