Version: Unity 6.7 Beta (6000.7)
LanguageEnglish
  • C#

ReleaseComponentResourcesAttribute

class in UnityEngine.UIElements

Suggest a change

Success!

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.

Close

Submission failed

For 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.

Close

Cancel

Description

Declares a static method of a VisualElementComponentAttribute struct that frees the resources the component allocated. It runs exactly once per component instance, on every path that releases the component, on the main thread.


The method must be static void M(ref T self), and a component may declare at most one. Free what this component allocated, and nothing else.

It runs on every path that releases the component: explicit removal with VisualElement.RemoveComponent or VisualElement.TryRemoveComponent, VisualElement.ReleaseResources, panel teardown, a recursive clear with VisualElementClearOptions.RecursiveReleaseResources, and garbage collection. Whichever path releases the component, the method is guaranteed to run, exactly once per component instance. The call is deferred to the next Collect() and always happens on the main thread.

The method receives no VisualElement. The element is unavailable by design, not by omission: the call is deferred to a main-thread drain that can run after the owning element has already been garbage-collected, and the element unlinks its component storage before that drain, so no element can be resolved at that point.

A component that holds a native container or an IDisposable field, directly or through a nested struct, must declare this method: releasing the component clears its storage with a raw memory copy, which drops the allocation without freeing it. The UITKSG050 diagnostic reports the omission as an error.

[OnComponentRemoved] is not an alternative. It runs only on an explicit VisualElement.RemoveComponent or VisualElement.TryRemoveComponent call, immediately and inline while the element is still alive, and it receives that element, so it may read its own state, touch the element, and add or remove components. It is skipped on element teardown and on garbage collection, so it is not guaranteed to run.

Rule of thumb: if you allocated it, free it in [ReleaseComponentResources]. If you want to react to a user removing your component, use [OnComponentRemoved]. Never rely on [OnComponentRemoved] to release anything.