Version: 2022.1
Relative and absolute positioning C# example
Best practices for managing elements

UQuery

You can use UQuery to retrieve elements from a visual treeAn object graph, made of lightweight nodes, that holds all the elements in a window or panel. It defines every UI you build with the UI Toolkit.
See in Glossary
. UQuery is based on JQuery or Linq, and is designed to limit dynamic memory allocation as much as possible. This allows for optimal performance on mobile platforms.

Retrieve elements

To use UQuery to retrieve elements, use the UQueryExtensions.Q or initialize a QueryBuilder with UQueryExtensions.Query.

For example, the following UQuery starts at the root and finds the first Button with the name foo:

root.Query<Button>("foo").First();

The following UQuery iterates, in the same group, on each Button named foo:

root.Query("foo").Children<Button>().ForEach(//do stuff);

Best practices

Consider the following when you use UQuery:

  • UQuery traverses through the hierarchy to find elements by name, class or type. Cache results from UQuery at initialization.
  • If you need to retrieve multiple elements, use the QueryState struct (returned by the element.Query() method) and enumerate it to avoid creating lists. You can also construct a query once and execute it on different elements.
  • UI(User Interface) Allows a user to interact with your application. Unity currently supports three UI systems. More info
    See in Glossary
    Toolkit doesn’t destroy visual elementsA node of a visual tree that instantiates or derives from the C# VisualElement class. You can style the look, define the behaviour, and display it on screen as part of the UI. More info
    See in Glossary
    that are no longer needed, it uses C# garbage collector to collect them. Be mindful to not accidentally retain references to visual elements in a class that outlives the UIDocuments or Window where the elements came from.
  • Capture VisualElement variables inside closures.
  • When you create or release lots of elements, enable incremental garbage collection to avoid garbage collector spikes.

Additional resources

Relative and absolute positioning C# example
Best practices for managing elements