Loading lessons...
UI Document & UXML
UI Document & UXML
UI Toolkit splits structure from styling. UXML (Unity Extensible Markup Language) defines the structure of your UI (similar to HTML).
UI Document Component
To render UI Toolkit interfaces in your scene:
- Create a GameObject.
- Add a UI Document component.
- Assign a Panel Settings asset (controls scaling and resolution).
- Assign a Source Asset (the UXML file).
The UI Builder
You create and edit UXML files visually using the UI Builder (Window -> UI Toolkit -> UI Builder):
- Hierarchy Panel: Shows the structure of your UI nodes (VisualElements, Labels, Buttons, TextFields).
- Library: Contains built-in elements you can drag into your UI.
- Viewport: The visual editing canvas.
- Inspector: Modifies names, text, and properties of selected elements.
Accessing UI Elements in C#
To interact with UI elements at runtime:
using UnityEngine;
using UnityEngine.UIElements;
public class GameMenu : MonoBehaviour
{
private Button startButton;
void OnEnable()
{
// Get the UIDocument component
var uiDoc = GetComponent<UIDocument>();
var root = uiDoc.rootVisualElement;
// Query the button by its name in UXML
startButton = root.Q<Button>("StartBtn");
// Register a click callback
startButton.clicked += OnStartClicked;
}
void OnStartClicked()
{
Debug.Log("Start Button Clicked!");
}
}
TL;DR
- UXML files define UI Toolkit layouts.
- UI Document component renders UXML files in the scene.
- Edit UXML files visually using the UI Builder tool.
- Use
rootVisualElement.Q<Type>("Name")to query elements in C#.