OnComponentRemovedAttribute
Declares a static method of a VisualElementComponentAttribute struct that runs when VisualElement.RemoveComponent removes the component from an element.
Read time 5 minutesLast updated 10 hours ago
Definition
- Type: Class
- Namespace: UnityEngine.UIElements
- Assembly: UnityEngine.UIElementsModule
- Inherits from: Attribute
[AttributeUsage(AttributeTargets.Method, Inherited = false)]public class OnComponentRemovedAttribute : Attribute
Remarks
The method must be , and a component may declare at most one. It runs before the component storage is freed and before its handlers are unregistered, so the method can still read its own live data and clean up any owner state the component configured.
static void M(ref T self, <see cref="UnityEngine.UIElements.VisualElement"></see> owner)[RegisterCallback]It runs only on an explicit VisualElement.RemoveComponent or VisualElement.TryRemoveComponent call, immediately and inline, while the element is still alive. Does not run when the element is released, when its panel is torn down, or when it is garbage-collected. It is therefore not guaranteed to run for a given component instance.
Because the method receives the owning element, it may read its own state, touch that element, and add or remove components. The component is still attached while the method runs, so removing it again, directly or from another component's method, calls the method again. A method that always removes its own component recurses without end, and so do two components that remove each other from these methods.
[OnComponentRemoved]To free something the component allocated, use [ReleaseComponentResources] instead. That hook is guaranteed to run exactly once per component instance, on every release path: explicit removal, VisualElement.ReleaseResources, panel teardown, a recursive clear with VisualElementClearOptions.RecursiveReleaseResources, and garbage collection. Its call is deferred to the next on the main thread, where the element may already have been collected, so it receives only its own data and no element, and may do nothing beyond freeing what the component allocated.
Collect()Rule of thumb: if you allocated it, free it in [ReleaseComponentResources]. If you want to react to a user removing your component, use . Never rely on to release anything.
[OnComponentRemoved][OnComponentRemoved]The parameter is valid only until the element's components change. For the rules that apply to it, refer to VisualElementComponentAttribute.
ref T self