Instantiating a Custom C# Control in Editor Script

Is it possible to instantiate a Custom C# Control via script similar to how a standard unity control can be added? Ex: Button vs CustomControl

The custom C# Control

internal class LocalizationEntryElement : VisualElement
{
    public string keyAttr { get; set; }
    public string valueAttr { get; set; }

    public new class UxmlFactory : UxmlFactory<LocalizationEntryElement, UxmlTraits>
    {
    }

    public new class UxmlTraits : VisualElement.UxmlTraits
    {
        readonly UxmlStringAttributeDescription m_StringKey =
            new UxmlStringAttributeDescription { name = "key-attr", defaultValue = "default_value" };

        readonly UxmlStringAttributeDescription m_StringValue =
            new UxmlStringAttributeDescription { name = "value-attr", defaultValue = "default_value" };

        public override IEnumerable<UxmlChildElementDescription> uxmlChildElementsDescription
        {
            get { yield break; }
        }

        public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
        {
            base.Init(ve, bag, cc);
            var ate = ve as LocalizationEntryElement;
            ate.keyAttr = m_StringKey.GetValueFromBag(bag, cc);
            ate.Add(new TextField("Id") { value = ate.keyAttr });
            ate.valueAttr = m_StringValue.GetValueFromBag(bag, cc);
            ate.Add(new TextField("Value") { value = ate.valueAttr });
        }
    }
}

The Editor Window

var uiAsset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Editor/LocalizationEditor.uxml");
var ui = uiAsset.CloneTree();
w.rootVisualElement.Add(ui);
//find the container
var row = w.rootVisualElement.Q<VisualElement>("EntryContainer");
//add the element to the container
row.Add(new Button());//this works
row.Add(new LocalizationEntryElement());//this does not work

This should work. What’s probably happening is that the LocalizationEntryElement has a height of 0. Changing its flex properties or forcing a non-zero height should make it appear.

You can open the UI Toolkit Debugger (Window > UI Toolkit > Debugger) to inspect the VisualElement hierarchy and debug those kinds of issues.

If you require sub-elements to be added in your control, you should do it in your control’s constructor. The factory/traits classes are only used when the control is created through uxml. Ideally, the Init() method should only be used to assign value to your control and not create its hierarchy.

Hope that helps.

Thank you I’m gonna try this.