Greetings!
I’ve been playing around with creating custom UI elements and I don’t quite understand how to change the default values of attributes that come from the element’s base class. For example, I created a simple TestField that inherits from BaseField:
public class TestField : BaseField<string>
{
public new class UxmlFactory : UxmlFactory<TestField, UxmlTraits> { }
public new class UxmlTraits : BaseFieldTraits<string, UxmlStringAttributeDescription>
{
private readonly UxmlBoolAttributeDescription extraAttribute = new UxmlBoolAttributeDescription { name = "extra-attribute", defaultValue = true };
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
// [...]
}
}
public TestField() : this(null, new TextField())
{ }
public TestField(string label, VisualElement visualInput) : base(label, visualInput)
{
// [...]
}
}
The BaseFieldTraits<> class I’m using includes several attributes we will have access to in UIBuilder through base.Init().
I would like to set different default values for some attributes (namely label and value), but I can’t figure out how to do it.
Unity’s own TextField, IntegerField and many others derive (directly or indirectly) from BaseField<>, and they have default values for their labels that are different than each other. I’ve peeked inside those components and couldn’t figure out how they do it.
I’ve tried setting the default label as a hardcoded value in the empty constructor call (line 16), but the UXMLTraits base overrides the label value with it’s own attribute.
