In this lesson, you will learn how to encapsulate basic UI elements into reusable, modular custom controls that act as single building blocks for your game’s interface.
Beyond Simple Prefabs
While you already know how to group VisualElements into hierarchies, manually recreating complex UI parts—like a specialized "Settings Toggle" or a "Character Health Bar"—is prone to errors and hard to maintain. Instead of copy-pasting, we build Custom Controls. A custom control is simply a C# class that inherits from VisualElement and defines its own structure, logic, and style internally.
Structuring Your Control
To create a custom control, you define a class that initializes its own internal child elements in its constructor. This allows you to treat a complex collection of images, labels, and buttons as a single, encapsulated object.
Here is a simplified example of how you might bundle a labeled button into a reusable component:
using UnityEngine.UIElements;
public class LabeledButton : VisualElement
{
public LabeledButton(string labelText, System.Action onClick)
{
// 1. Create internal elements
var label = new Label(labelText);
var button = new Button(onClick) { text = "Click Me" };
// 2. Add them to this component
Add(label);
Add(button);
// 3. Apply styles internally
this.AddToClassList("labeled-button-container");
}
}
Why Modularize?
When you define a class like LabeledButton, you hide the internal hierarchy from the rest of your project. If you decide to change the layout or add an icon to every button in your game later, you only need to update the logic inside this one class. You can then instantiate these controls directly in your C# scripts using rootVisualElement.Add(new LabeledButton("Start", StartGame));.
By treating UI components as black boxes, you keep your UIDocument trees clean and your logic focused on high-level orchestration rather than low-level element manipulation. This approach transforms your UI from a fragile tangle of nested objects into a reliable library of parts.
Key Takeaway: Building custom UI controls allows you to encapsulate complex visual trees into single, reusable objects that promote consistency, simplify maintenance, and keep your UI architecture clean.