VisualElementComponentAttribute
Declares a struct as a UI Toolkit component: a reusable piece of data and behavior that you can attach to any VisualElement.
Read time 5 minutesLast updated 4 days ago
Definition
- Type: Class
- Namespace: UnityEngine.UIElements
- Assembly: UnityEngine.UIElementsModule
- Inherits from: Attribute
[AttributeUsage(AttributeTargets.Struct, Inherited = false)]public class VisualElementComponentAttribute : Attribute
Remarks
Components extend elements through composition instead of inheritance. Rather than writing a custom element subclass, declare a with this attribute and attach an instance to any element with VisualElement.AddComponent. The same component type works on any element, whatever its type.
partial structThis attribute targets structs. The struct must be declared : Unity's source generator completes it, implementing IVisualElementComponent and generating the registration code for you.
partialAn element holds at most one component of each type. Read or modify an attached component with VisualElement.GetComponent; remove it with VisualElement.RemoveComponent.
Add HideInInspector to the struct to keep the component out of every editor surface: the VisualElement inspector, the UI Builder inspector, and the UI Toolkit Debugger. This is independent of _exposeToUxml, which decides only UXML authoring.
The following example attaches a click counter to a button without subclassing it.
Examples
using UnityEngine;using UnityEngine.UIElements;[VisualElementComponent]public partial struct ClickCounter{ public int count;}public static class ClickCounterExample{ public static void Attach(Button button) { // Attach the component with its starting value. button.AddComponent(new ClickCounter { count = 0 }); button.RegisterCallback<ClickEvent>(evt => { // GetComponent returns a reference: the increment is stored on the element. ref var counter = ref button.GetComponent<ClickCounter>(); counter.count++; Debug.Log($"Clicked {counter.count} times."); }); }}
Fields
Value | Description |
|---|---|
| initialCapacity | The number of storage slots Unity reserves up front for this component type. Set it to roughly how many elements you expect to carry this component at the same time. |
| name | The name that identifies this component in UXML. If not set, the struct's name is used. |
Constructors
Constructor | Description |
|---|---|
| VisualElementComponentAttribute(System.Boolean) | Initializes a new instance of the VisualElementComponentAttribute class. |
Properties
Property | Description |
|---|---|
| exposeToUxml | Whether the component can be authored in UXML. The fields marked UxmlAttributeAttribute define the component's authorable surface either way; this flag only decides whether UXML sees it. Pass |