Search Unity

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

Discussion in 'UI Toolkit' started by LaneFox, Aug 13, 2020.

  1. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,536
    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?
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,338
    Pretty sure you're supposed to use the Query system for that:

    Code (csharp):
    1. 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:

    Code (csharp):
    1. root.Q<VisualElement>("some_container").Q<Button>("nested_button")
     
    Bovine likes this.
  3. JakHussain

    JakHussain

    Joined:
    Oct 20, 2016
    Posts:
    318
    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.
     
  4. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,338
    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.
     
    uDamian likes this.
  5. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,536
    This worked great, thanks @Baste