Search Unity

  1. Looking for a job or to hire someone for a project? Check out the re-opened job forums.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Accessing multiple elements in UIDocument by class or type

Discussion in 'UI Toolkit' started by tacman1123, Nov 22, 2020.

  1. tacman1123

    tacman1123

    Joined:
    Sep 14, 2020
    Posts:
    56
    The Q() method appears to return only on element, by name (or by class, but only one element).

    I'm thinking of jQuery, where you can add a handler to all elements of a class with something like $('.danger').onClick( ... ).

    So this works:
    Code (CSharp):
    1.        
    2. Button startButton = root.Q<Button>("start-button");
    3.         startButton.clickable = new Clickable(() =>
    4.         {
    5.             SceneManager.LoadScene("AppScene");
    6.         });
    7.  
    8. // var sceneButtons  = root.Q<Button>(null, ["scene-button"]); // returns just the first one
    9.  
    For example, how would I look for all buttons with a "scene-class" and assign this callback? I could then map the button name to the scene I wanted to load, or (ideally) get some data from the button itself. Maybe with the binding path or view data key?

    I guess I could go through all the children of UIDocument, but that doesn't seem right. Is there a way to get a list of all the elements matching a class under the root?

    Thanks,

    Tac
     
  2. MousePods

    MousePods

    Joined:
    Jul 19, 2012
    Posts:
    245
  3. tacman1123

    tacman1123

    Joined:
    Sep 14, 2020
    Posts:
    56
    Yep, perfect, thanks. So there's a UQuery method that is inspired by jQuery, exactly what I was looking for! And the Query() method will likely be the one I actually use.
     
    MousePods likes this.
unityunity