Documentation

Unity Engine

Download Unity

Unity Engine

OnComponentAddedAttribute

Declares a static method of a VisualElementComponentAttribute struct that runs once, right after the component is added to an element.
Read time 4 minutesLast updated 10 hours ago

Definition

[AttributeUsage(AttributeTargets.Method, Inherited = false)]public class OnComponentAddedAttribute : Attribute

Remarks

The method must be
static void M(ref T self, <see cref="UnityEngine.UIElements.VisualElement"></see> owner)
, and a component may declare at most one. It runs on every add path:
AddComponent
,
GetOrAddComponent
, a component authored in UXML, and a [RequiresComponentOfType] auto-add. It runs after the component is stored and its
[RegisterCallback]
handlers are registered, so the method sees a fully wired component and may configure the owner element (for example set
owner.focusable
). On the UXML path it runs when the component is created, before the authored attribute values are applied, so authored values always win over values this method writes to the component. When the component is auto-added for a [RequiresComponentOfType] requirement, the method must not add the component that requires it, because that component is already being added: in the Editor, the
AddComponent
or
GetOrAddComponent
call that started the add throws InvalidOperationException.
When this method runs, the component exists on the element, but its data might not be final. On the UXML and template paths, Unity applies the authored values after this method runs. To configure the owner element from the component's field values, use [OnComponentChanged] instead, which runs after the data is in place.
The
ref T self
parameter is valid only until the element's components change. For the rules that apply to it, refer to VisualElementComponentAttribute.

Inheritance

Inherited Members