Skip to content

2. UxmlFactory & UxmlTraits generation

Joni Savolainen edited this page Jun 2, 2023 · 4 revisions

UIComponents offers ways to generate a UxmlFactory and UxmlTraits implementation for your VisualElements. You do not need to inherit from UIComponent to use them.

UxmlNameAttribute

Apply [UxmlName(...)] to a class to generate a UxmlFactory implementation for it which defines the element's UXML name.

using UIComponents;

[UxmlName("Button")]
public partial class ButtonComponent : UIComponent {}

This generates:

public partial class ButtonComponent 
{
    public new class UxmlFactory : UxmlFactory<ButtonComponent>
    {
        public override string uxmlName
        {
            get { return "Button"; }
        }

        public override string uxmlQualifiedName
        {
            get { return uxmlNamespace + "." + uxmlName; }
        }
    }
}

UxmlTraitAttribute

Basic usage

Apply [UxmlTrait] to a field or property to generate a UxmlTraits implementation for it.

using UIComponents;

public partial class MyComponent : UIComponent
{
    [UxmlTrait]
    public string DescriptionText;
}

This generates:

public partial class MyComponent
{
    public new class UxmlFactory : UxmlFactory<MyComponent, UxmlTraits> {}

    public new class UxmlTraits : UIElements.UxmlTraits
    {
        UxmlStringAttributeDescription m_Description = new UxmlStringAttributeDescription { name = "description-text" };

        public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
        {
            base.Init(ve, bag, cc);
            ((MyComponent)ve).DescriptionText = m_Description.GetValueFromBag(bag, cc);
        }
    }
}

Note how a kebab-case version of the member name is used for the trait by default.

Custom name

To change the name of the UXML attribute, use the Name property:

[UxmlTrait(Name = "component-description")]
public string Description;

Default value

The member's initializer is used as the default value.

[UxmlTrait]
public string Description = "None set";

Supported types

UxmlTraitAttribute supports all types supported by UIToolkit.

  • string
  • float
  • double
  • int
  • long
  • bool
  • UnityEngine.Color
  • Enum