How to create custom VisualElement from code with UXML template?

  1. I’ve created visual element in builder and name it MyCustomVisualElement.uxml

  2. I’ve created C# control for this

[UxmlElement]
public partial class MyCustomVisualElement : VisualElement
{
    public MyCustomVisualElement()
    {
    }
}
  1. Now I just want to create this from code like this:
MyCustomVisualElement myCustomVisualElement= new MyCustomVisualElement();
listView.hierarchy.Add(myCustomVisualElement);

I am expecting that uxml template from builder will be created and linked with control automatically because it has THE SAME NAME. But its not, so maybe I have to add some tag in uxml so Unity will understand that

Important note: I don’t want to use Resources.Load(“MyCustomVisualElement”) inside the custom controller constructor. This is a dealbreaker for me. If Unity with all its power can’t handle the link between uxml and customControl automaticaly, I am not going to use UI Elements. Thanks

You’re going to have to reference the visual tree asset in some form to be able to instantiate it. How is Unity going to know where to look up the asset? It could be in Resources, an Asset Bundle, Addressables Groups, anywhere. You’ll have to put that work in yourself.