Skip to content

2. UxmlFactory & UxmlTraits generation

Joni Savolainen edited this page Oct 22, 2022 · 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;
using UIComponents.Experimental;

[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;
using UIComponents.Experimental;

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).Description = 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 default value can be set using the DefaultValue property:

[UxmlTrait(DefaultValue = "None set")]
public string Description;

Supported types

UxmlTraitAttribute supports all types supported by UIToolkit.

  • string
  • float
  • double
  • int
  • long
  • bool
  • UnityEngine.Color
  • Enum
Clone this wiki locally