// Build and optimize Unity UI with UI Toolkit and UGUI. Masters responsive layouts, event systems, and performance optimization. Use for UI implementation, Canvas optimization, or cross-platform UI challenges.
| name | unity-ui |
| description | Build and optimize Unity UI with UI Toolkit and UGUI. Masters responsive layouts, event systems, and performance optimization. Use for UI implementation, Canvas optimization, or cross-platform UI challenges. |
Unity UI systems covering both UI Toolkit (modern) and UGUI (Canvas-based legacy).
Core Topics:
using UnityEngine.UI;
public class UIController : MonoBehaviour
{
[SerializeField] private Button actionButton;
[SerializeField] private Text statusText;
void Start()
{
actionButton.onClick.AddListener(OnButtonClick);
}
void OnButtonClick()
{
statusText.text = "Button clicked!";
}
}
using UnityEngine.UIElements;
public class UIController : MonoBehaviour
{
void OnEnable()
{
var root = GetComponent<UIDocument>().rootVisualElement;
var button = root.Q<Button>("action-button");
button.clicked += OnButtonClick;
}
void OnButtonClick()
{
Debug.Log("Button clicked!");
}
}
| Feature | UI Toolkit | UGUI |
|---|---|---|
| Performance | Better | Good |
| Styling | USS (CSS-like) | Inspector |
| Layout | Flexbox | RectTransform |
| Best For | Complex UI, tools | Game UI |
| Learning Curve | Steeper | Easier |
// Separate static and dynamic UI into different canvases
// Static canvas: rarely changes
// Dynamic canvas: updates frequently
// Disable raycasting on non-interactive elements
[SerializeField] private Image background;
void Start()
{
background.raycastTarget = false; // Not clickable
}
// Use CanvasGroup for fade effects
CanvasGroup canvasGroup = panel.GetComponent<CanvasGroup>();
canvasGroup.alpha = 0.5f; // Fade without rebuilding Canvas
// Use anchors for responsive design
// Anchor presets: Stretch, Top-Left, Center, etc.
// Canvas Scaler settings
var scaler = GetComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
scaler.referenceResolution = new Vector2(1920, 1080);
scaler.matchWidthOrHeight = 0.5f; // Balance between width/height