How do I get specific elements from a UXML layout in code?

I used UI Builder to build some layout and popped it into an EditorWindow. Great. Now how do I connect to specific buttons, lists and toolbar items in my code?

I don’t really see any convenient way to access the tree of VisualElements and fetch items by name, or declare them ahead of time so I can fetch them later easily. What am I missing?

Pretty sure you’re supposed to use the Query system for that:

root.Q<Button>("button_name") ...

If you don’t want unique names for every single element, you can Q a part of the UI and then Q it’s nested elements:

root.Q<VisualElement>("some_container").Q<Button>("nested_button")
1 Like

is there any plan to move away from these explicit string based names or provide some alternative? There’s so much room for human error with an API like this.

Well, the input format is a xml document, so it’s pretty much bound to be string-based.

If you don’t like that, you can always build the ui from pure C#, and wrap each element with something that has a strong binding. I have done that, it’s pretty comfortable.

It’s probably not worthwhile, but it would be possible to do a code-gen thing on the xml document in order to generate that wrapper. I don’t think Unity should spend their resources on that, though.

1 Like

This worked great, thanks @Baste