UxmlCreateInstanceMethodAttribute
Declares a method to create instances in place of the default constructor.
Read time 4 minutesLast updated 4 days ago
Definition
- Type: Class
- Namespace: UnityEngine.UIElements
- Assembly: UnityEngine.UIElementsModule
- Inherits from: Attribute
[AttributeUsage(AttributeTargets.Method)]public class UxmlCreateInstanceMethodAttribute : Attribute
Remarks
Use this to provide custom instance creation logic, such as object pooling, dependency injection, or default values for a component. Three callers use the method: UXML instantiation (element and component defaults), when it creates a missing component, and a RequiresComponentOfTypeAttribute auto-add. The method must meet the following requirements:
GetOrAddComponent-
Be a static method defined on the element type.
-
Have public or internal accessibility.
-
Accept no parameters.
-
Not be generic.
-
Return an instance of the element type (or null to fall back to the default constructor).
If this attribute is not found on the element, the source generator uses the default constructor (). If the method returns null, the source generator uses the default constructor as a fallback.
new T()The following example uses a custom creation method for object pooling:
Examples
using UnityEngine.UIElements;using UnityEngine.Pool;namespace MyNamespace{ [UxmlElement] public partial class MyButtonElement : Button { [UxmlCreateInstanceMethodAttribute] public static MyButtonElement CreateInstance() { return GenericPool<MyButtonElement>.Get(); } }}