Skip to content

t1k:unity:ui:ugui

FieldValue
Moduleui
Version3.43.4
Efforthigh
Tools—

Keywords: 9-slice, canvas, label clipped, min font size, slice border, text clipped, text contrast, text fit, uGUI, unity ui

/t1k:unity:ui:ugui

Canvas-based UI for Unity 6. Use for gameplay HUD, menus, inventory grids, health bars. For Editor UI or data-heavy panels, prefer UI Toolkit (t1k-unity-ui-toolkit skill).

Architecture-neutral. Everything below applies to plain MonoBehaviour projects. The DOTS bridge is ONE section (§ “DOTS ECS Bridge”) and applies only when the project uses DOTS — i.e. its Packages/manifest.json lists com.unity.entities, not merely that dots-core is installed. In a MonoBehaviour project, skip it and bind UI directly to MonoBehaviours/events.

FeatureuGUI (Canvas)UI Toolkit
Runtime game UIPreferredSupported (Unity 6+)
World-space UINative supportNot supported
Drag-and-dropBuilt-in interfacesManual
Editor extensionsNot supportedPreferred
Animation/tweeningDOTween/LitMotionUSS transitions
TextMeshProNative integrationBuilt-in text
// Screen-space overlay (HUD) — no camera needed
var canvasGO = new GameObject("Canvas", typeof(Canvas), typeof(CanvasScaler), typeof(GraphicRaycaster));
var canvas = canvasGO.GetComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
canvas.sortingOrder = 10;
var scaler = canvasGO.GetComponent<CanvasScaler>();
scaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
scaler.referenceResolution = new Vector2(1920, 1080);
scaler.matchWidthOrHeight = 0.5f; // blend width/height matching
// EventSystem (required for clicks/drags)
if (Object.FindAnyObjectByType<UnityEngine.EventSystems.EventSystem>() == null)
{
var esGO = new GameObject("EventSystem",
typeof(UnityEngine.EventSystems.EventSystem),
typeof(UnityEngine.InputSystem.UI.InputSystemUIInputModule));
}

→ See references/components-quick-ref.md for Image, RawImage, TMP, Button, Toggle, Slider, Dropdown, InputField.

// Stretch to fill parent
rt.anchorMin = Vector2.zero; // bottom-left
rt.anchorMax = Vector2.one; // top-right
rt.offsetMin = Vector2.zero; // left/bottom padding
rt.offsetMax = Vector2.zero; // right/top padding
// Fixed size, anchored top-left
rt.anchorMin = rt.anchorMax = new Vector2(0, 1); // top-left
rt.pivot = new Vector2(0, 1);
rt.anchoredPosition = new Vector2(10, -10);
rt.sizeDelta = new Vector2(200, 50);
// Fixed size, centered
rt.anchorMin = rt.anchorMax = new Vector2(0.5f, 0.5f);
rt.pivot = new Vector2(0.5f, 0.5f);
rt.anchoredPosition = Vector2.zero;
rt.sizeDelta = new Vector2(300, 300);
// Grid layout (inventory slots)
var grid = parent.gameObject.AddComponent<GridLayoutGroup>();
grid.cellSize = new Vector2(64, 64);
grid.spacing = new Vector2(4, 4);
grid.constraint = GridLayoutGroup.Constraint.FixedColumnCount;
grid.constraintCount = 8; // 8 columns
grid.childAlignment = TextAnchor.UpperLeft;

→ See references/layouts-and-drag-drop.md for HorizontalLayout, ScrollRect, drag-and-drop. In a DOTS project, reusable grid cells can implement IInventoryGridCellHandler (DOTSUI) — see t1k-unity-dots-inventory-grid.

Skip unless the project uses DOTS (Packages/manifest.json lists com.unity.entities). MonoBehaviour projects render the same Canvas with no EntityManager/World/EntityQuery anywhere — bind to events, [SerializeField] refs, or a presenter instead.

// MonoBehaviour reads ECS data each frame for UI updates
public class InventoryUI : MonoBehaviour {
private EntityManager _em;
private EntityQuery _playerQuery;
void Start() {
_em = World.DefaultGameObjectInjectionWorld.EntityManager;
_playerQuery = _em.CreateEntityQuery(typeof(PlayerTag));
}
void LateUpdate() {
if (_playerQuery.IsEmpty) return;
var entity = _playerQuery.GetSingletonEntity();
var grid = _em.GetBuffer<InventoryGridCell>(entity);
// Update UI from grid buffer...
}
}

→ See references/dots-bridge-and-performance.md for full patterns.

  1. raycastTarget — disable on decorative Text/Image (perf)
  2. Canvas rebuild — separate dynamic from static canvases
  3. InputSystemUIInputModule required — replaces StandaloneInputModule
  4. TMP only — always TextMeshProUGUI, never UnityEngine.UI.Text
  5. World-space Canvas — needs EventCamera set for raycasts
  6. Layout rebuilds — LayoutRebuilder.ForceRebuildLayoutImmediate() if reading size same frame
  7. ScreenSpaceOverlay not captured by Camera.Render() — screenshots taken from a camera miss an overlay Canvas; use ScreenSpaceCamera if you need camera captures to include UI
  8. Camera setup for ScreenSpaceCamera — assign canvas.worldCamera = Camera.main; canvas.planeDistance = 10f; and set camera’s culling mask to include UI layer
  9. GridLayoutGroup + SetActive(false) — never use SetActive(false) on grid cell GameObjects; GridLayoutGroup collapses hidden children, breaking cell positions. Instead, hide visuals (disable Image/CanvasGroup.alpha = 0) while keeping the GameObject active
  10. NEVER use ?? with Unity objects — GetComponent<T>() ?? AddComponent<T>() silently fails because C# ?? bypasses Unity’s overridden == null. Always use: var c = GetComponent<T>(); if (c == null) c = AddComponent<T>();
  11. NEVER use HasComponent<EnumType>() in ECS (DOTS projects) — Enums are NOT components. Access via em.GetComponentData<Item>(e).Rarity instead.
  12. CanvasScaler portrait setup: For portrait-locked mobile games, use referenceResolution = new Vector2(1080, 1920) with matchWidthOrHeight = 0.5f. Do NOT use match=1.0 — it causes text to shrink on wider phones (18:9, 20:9). The 0.5 blend keeps text readable across all common mobile aspect ratios. Notch/cutout devices additionally need an explicit safe-area parent (set the top-level layout RectTransform’s anchors from Screen.safeArea at runtime) — matchWidthOrHeight alone does not protect content from the cutout. See t1k-unity-ui-mobile-ui.
  13. Screen Space Overlay not captured by Camera.Capture: a camera screenshot won’t show Overlay Canvas UI (and the t1k unity facade has no screenshot verb). To verify Overlay UI, read component properties with t1k unity eval in Play mode, or ask the user for a Game-view capture.
  14. active=true ≠ UI works — see “UI Behavior Validation” section below. A panel can be on-screen, scale-resolved, AND completely empty/non-functional because the populate path was never called. State-only Play-mode checks lie.
  15. Template-spawn pattern is a hidden runtime contract — if a screen has a child named *Template, *Prefab, or *Slot that’s hidden on start, the screen expects an external caller to invoke a populate method (typically SetEntries, Populate, Bind, Refresh). The method existing in the screen class proves nothing — grep the codebase for call sites. Zero external call sites = the feature is unfinished.
  16. Deferred-work comments are red flags, not annotations — // Phase F wires the roster source, // for now Show(true) is sufficient, // TODO: populate from registry mean the UI is half-built. Treat as “broken” until proven otherwise; never validate only the panel container.
  17. HLG/VLG do not size children by default — set childControlWidth/childControlHeight true and stretch the child anchors, or children extrude and steal raycasts. Full text: gotcha ledger g-t1k-unity-ui-ugui-02.
  18. A locked-only panel is hidden, not re-laid-out — SetActive(false) and re-enable on unlock. Full text: gotcha ledger g-t1k-unity-ui-ugui-03.
  19. An opaque full-screen Image on a ScreenSpaceOverlay Canvas hides the 3D scene — grep prefabs for it before blaming the camera. Full text: gotcha ledger g-t1k-unity-ui-ugui-04.
  20. Pivot must match anchor on corner-anchored RectTransforms — when anchorMin == anchorMax, set pivot = anchorMin. Full text: gotcha ledger g-t1k-unity-ui-ugui-05.
  21. A TMP glyph box and a literal <sprite> tag are two different silent failures — diagnosis in gotcha ledger g-t1k-unity-ui-ugui-06 and references/tmp-inline-sprites.md.
  22. TMP outline set from code does not serialize — assign a committed Material asset to fontSharedMaterial. Full text: references/hard-rules-details.md #22.
  23. TMP alignment serializes as the H/V pair, not m_textAlignment — verify against the loaded asset, never the YAML you wrote. Full text: references/hard-rules-details.md #23.
  24. A reversed world-space Canvas loses its raycasts silently — turn ignoreReversedGraphics off, and diagnose with two raycast layers. Full text: gotcha ledger g-t1k-unity-ui-ugui-07.
  25. One Text has one font — a localized label plus player text needs two Text components when the name needs another face. Full text: references/hard-rules-details.md #25.
  26. Sliced Image with a zero sprite border draws Simple, silently (also after a runtime .sprite swap) — checklist: t1k-unity-base-asset-import/references/slicing.md

Two recurring HUD bugs the unity-hud-layout skill exists to prevent:

  • Never stack widgets via absolute pixel offsets on the same RectTransform — each new widget invents a new offset, and the first text-size or font change cascades into visible overlap. When >3 widgets share a RectTransform, split the parent into named zones with LayoutGroups; each new widget picks a zone, not a pixel offset.

State-only validation (active=true, scale != (0,0,0)) misses the most common uGUI failure mode: panel opens, panel is empty/dysfunctional — all state checks pass while SetEntries(...) (or equivalent populator) is never called by any external caller, or a confirm button stays interactable=false forever. Required behavior probes per panel (list population child-count, button onClick wiring, dynamic-label non-empty, interactable-state gating) and the diagnostic recipe for “I see the panel but X doesn’t work”: references/play-mode-validation.md.

Frame fit checklist (plates, panels, sliced backgrounds)

Section titled “Frame fit checklist (plates, panels, sliced backgrounds)”

Run it before a frame, plate or background counts as done. Formulas, the test recipe and the measurement method: references/frame-fit.md. Sprite border SSOT: t1k-unity-base-asset-import/references/slicing.md.

  • Border from the .meta, not a code table. spriteBorder: {x: left, y: bottom, z: right, w: top}. A test reads the .meta and the table in both directions. A Sliced image whose sprite border is zero draws Simple, silently.
  • Border fits the rect. Border sum < sprite side. Rect ≥ border sum ÷ (PPU × pixelsPerUnitMultiplier) on each axis.
  • Simple vs Sliced is a choice. Simple stretches the whole bitmap; Sliced keeps the corners. Never Filled or Tiled with a border.
  • Panel background alpha 1.0. Rect = content + padding; the height comes from the layout, never from an independent constant.
  • Plate vs content in screen px at 540x960, 1080x1920 and 1080x2340 (portrait). Content sits inside the plate with padding on every side.
  • Contrast. Text against its own plate: ≥ 4.5:1 for body text, ≥ 3:1 for large text and names.
  • Chrome clearance. A modal’s close control clears the nav-bar labels. Child rows that share a visual line align their edges within 2 px.

A frame is done when a test asserts the relation (content inside the plate, alpha 1, non-zero border) and a render at the three sizes was looked at. A number pinned to today’s layout is not proof.

FileContent
references/components-quick-ref.mdImage, RawImage, TMP, Button, Toggle, Slider, Dropdown, InputField
references/layouts-and-drag-drop.mdLayout groups, ScrollRect, IBeginDragHandler/IDragHandler/IDropHandler
references/dots-bridge-and-performance.mdECS→UI data flow (DOTS projects only), Canvas batching, pooling, split canvases
references/incident-log.mdDated postmortems behind the gotchas above — reproduction, root cause, exact fix location
references/tmp-inline-sprites.mdTMP <sprite> tag syntax + resolution order, the tofu-box vs literal-tag-text failure-mode diagnosis, the spriteCount false-negative trap
references/tmp-sprite-asset-setup.mdDiagnosing the tofu box against the font’s baked glyph table, TMP_SpriteAsset setup (Editor and data-only YAML paths), EditMode-testable checks for both failure modes
references/tmp-prefab-yaml.mdHand-editing TMP in prefab YAML — the live m_HorizontalAlignment/m_VerticalAlignment pair vs the legacy m_textAlignment 65535 sentinel, why LoadDefaultSettings() re-migration clobbers the edit, and verifying via the loaded asset
references/frame-fit.mdFrame fit detail: border-from-.meta test in both directions, border-vs-rect formula, Simple vs Sliced, panel alpha and content-driven height, the three-size measurement method, WCAG contrast helper, dark ink on a near-black outline, lightest-5% plate contrast
references/hard-rules-details.mdVerbatim full text of hard rules #22, #23, #25 (TMP outline serialization, TMP alignment pair, one font per Text)
references/layout-qa-playbook.mdMeasurable layout QA rules: label pad inside plates, thumbnail minimums and scroll reachability, CJK line breaking, localization widows, close-control clearance, NOT-A-DEFECT records, stale frames, harness false positives, pixel measurement recipe, CJK and spaced-script orphans, canvas units vs screen px, tap-target hit rects

A visible change made with this skill (UI, sprites, 3D, shaders, VFX, animation, lighting, scene layout; audio excluded) follows core rule visual-change-discord-notice:

  • Capture OLD before the first edit and NEW after the last (screen: ScreenCapture in Play mode per t1k-unity-editor-cli, windowed or Xvfb only because rendering is needed; 3D, shader, VFX: same-scene frame grab; 2D asset: the file).
  • Return the paths and a draft Discord post to the orchestrator, which posts; the PR links the post or carries visual-notice-waiver: <reason>. Logic only: “no visible change”. No capture: “screenshots pending: ”, never a fake image.