---
description: UI Systems
alwaysApply: false
---

# UI Systems

Guidelines for building runtime user interfaces in Unity using UI Toolkit and UGUI.

## Core Principles

- Separate UI logic (presenter) from layout (view) and game state (model)
- UI Toolkit for new projects with complex layouts; UGUI for world-space and VR
- Design responsive layouts for different screen sizes and safe areas
- Minimize Canvas rebuilds (UGUI) and USS recalculations (UI Toolkit)

## System Selection

| Criteria | UI Toolkit | UGUI |
|----------|-----------|------|
| New runtime UI | Preferred | Acceptable |
| World-space / VR | Limited | Preferred |
| Data binding | Built-in | Manual |
| Layout system | Flexbox (USS) | RectTransform anchors |
| Editor extensions | Primary choice | Legacy |

## MVP Architecture

- **Model** (ScriptableObject / C#): Game state data, raises change events, no UI refs
- **Presenter** (MonoBehaviour): Queries view in OnEnable, subscribes to model, forwards input
- **View** (UXML+USS / Canvas): Pure layout and style, no game logic

## UGUI Performance

| Problem | Solution |
|---------|----------|
| Canvas rebuild spikes | Split static/dynamic into sub-canvases |
| Nested LayoutGroup stutter | Avoid nesting > 2 levels |
| Overdraw on mobile | Reduce layers, sprite packing |
| Raycast on everything | Disable Raycast Target on non-interactive elements |

Rule: Elements that change together share a Canvas. Different update rates get separate Canvases.

## Responsive Design

| Platform | Strategy | Key Consideration |
|----------|----------|-------------------|
| Mobile | Flex column | Touch target min 44x44 dp |
| Desktop | Fixed or scaled | Mouse hover states |
| Console TV | Overscan safe area | Large text, 10-foot UI |
| VR | World-space 2-3m | No small text, gaze targets |

## Common Pitfalls

**Querying Elements Every Frame**: Calling `root.Q<Label>("score")` in Update. Cache the reference in OnEnable.

**Ignoring Raycast Target**: Leaving it enabled on all Images and Text. Disable on non-interactive elements.

**Hardcoded Pixel Sizes**: Use USS relative units, CanvasScaler with reference resolution, or DPI scaling.
