t1k:unity:ui:ugui
| Field | Value |
|---|---|
| Module | ui |
| Version | 3.43.4 |
| Effort | high |
| Tools | — |
Keywords: 9-slice, canvas, label clipped, min font size, slice border, text clipped, text contrast, text fit, uGUI, unity ui
How to invoke
Section titled “How to invoke”/t1k:unity:ui:uguiUnity uGUI (Canvas UI)
Section titled “Unity uGUI (Canvas UI)”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.
When to Use uGUI vs UI Toolkit
Section titled “When to Use uGUI vs UI Toolkit”| Feature | uGUI (Canvas) | UI Toolkit |
|---|---|---|
| Runtime game UI | Preferred | Supported (Unity 6+) |
| World-space UI | Native support | Not supported |
| Drag-and-drop | Built-in interfaces | Manual |
| Editor extensions | Not supported | Preferred |
| Animation/tweening | DOTween/LitMotion | USS transitions |
| TextMeshPro | Native integration | Built-in text |
Canvas Setup (Programmatic)
Section titled “Canvas Setup (Programmatic)”// Screen-space overlay (HUD) — no camera neededvar 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.
RectTransform Anchoring
Section titled “RectTransform Anchoring”// Stretch to fill parentrt.anchorMin = Vector2.zero; // bottom-leftrt.anchorMax = Vector2.one; // top-rightrt.offsetMin = Vector2.zero; // left/bottom paddingrt.offsetMax = Vector2.zero; // right/top padding
// Fixed size, anchored top-leftrt.anchorMin = rt.anchorMax = new Vector2(0, 1); // top-leftrt.pivot = new Vector2(0, 1);rt.anchoredPosition = new Vector2(10, -10);rt.sizeDelta = new Vector2(200, 50);
// Fixed size, centeredrt.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);Layout Groups
Section titled “Layout Groups”// 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 columnsgrid.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.
DOTS ECS Bridge (DOTS projects only)
Section titled “DOTS ECS Bridge (DOTS projects only)”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 updatespublic 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.
Hard rules
Section titled “Hard rules”- raycastTarget — disable on decorative Text/Image (perf)
- Canvas rebuild — separate dynamic from static canvases
- InputSystemUIInputModule required — replaces StandaloneInputModule
- TMP only — always TextMeshProUGUI, never UnityEngine.UI.Text
- World-space Canvas — needs EventCamera set for raycasts
- Layout rebuilds —
LayoutRebuilder.ForceRebuildLayoutImmediate()if reading size same frame - 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
- Camera setup for ScreenSpaceCamera — assign
canvas.worldCamera = Camera.main; canvas.planeDistance = 10f;and set camera’s culling mask to include UI layer - GridLayoutGroup + SetActive(false) — never use
SetActive(false)on grid cell GameObjects;GridLayoutGroupcollapses hidden children, breaking cell positions. Instead, hide visuals (disableImage/CanvasGroup.alpha = 0) while keeping the GameObject active - 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>(); - NEVER use
HasComponent<EnumType>()in ECS (DOTS projects) — Enums are NOT components. Access viaem.GetComponentData<Item>(e).Rarityinstead. - CanvasScaler portrait setup: For portrait-locked mobile games, use
referenceResolution = new Vector2(1080, 1920)withmatchWidthOrHeight = 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 fromScreen.safeAreaat runtime) —matchWidthOrHeightalone does not protect content from the cutout. Seet1k-unity-ui-mobile-ui. - Screen Space Overlay not captured by Camera.Capture: a camera screenshot won’t show Overlay Canvas UI (and the
t1k unityfacade has no screenshot verb). To verify Overlay UI, read component properties witht1k unity evalin Play mode, or ask the user for a Game-view capture. 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.- Template-spawn pattern is a hidden runtime contract — if a screen has a child named
*Template,*Prefab, or*Slotthat’s hidden on start, the screen expects an external caller to invoke a populate method (typicallySetEntries,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. - Deferred-work comments are red flags, not annotations —
// Phase F wires the roster source,// for now Show(true) is sufficient,// TODO: populate from registrymean the UI is half-built. Treat as “broken” until proven otherwise; never validate only the panel container. - HLG/VLG do not size children by default — set
childControlWidth/childControlHeighttrue and stretch the child anchors, or children extrude and steal raycasts. Full text: gotcha ledger g-t1k-unity-ui-ugui-02. - 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. - An opaque full-screen
Imageon 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. - Pivot must match anchor on corner-anchored RectTransforms — when
anchorMin == anchorMax, setpivot = anchorMin. Full text: gotcha ledger g-t1k-unity-ui-ugui-05. - A TMP glyph box and a literal
<sprite>tag are two different silent failures — diagnosis in gotcha ledger g-t1k-unity-ui-ugui-06 andreferences/tmp-inline-sprites.md. - TMP outline set from code does not serialize — assign a committed Material asset to
fontSharedMaterial. Full text:references/hard-rules-details.md#22. - 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. - A reversed world-space Canvas loses its raycasts silently — turn
ignoreReversedGraphicsoff, and diagnose with two raycast layers. Full text: gotcha ledger g-t1k-unity-ui-ugui-07. - One
Texthas one font — a localized label plus player text needs twoTextcomponents when the name needs another face. Full text:references/hard-rules-details.md#25. - Sliced Image with a zero sprite border draws Simple, silently (also after a runtime
.spriteswap) — 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.
UI Behavior Validation (Play-Mode Probes)
Section titled “UI Behavior Validation (Play-Mode Probes)”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.metaand 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
FilledorTiledwith 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.
Reference Files
Section titled “Reference Files”| File | Content |
|---|---|
references/components-quick-ref.md | Image, RawImage, TMP, Button, Toggle, Slider, Dropdown, InputField |
references/layouts-and-drag-drop.md | Layout groups, ScrollRect, IBeginDragHandler/IDragHandler/IDropHandler |
references/dots-bridge-and-performance.md | ECS→UI data flow (DOTS projects only), Canvas batching, pooling, split canvases |
references/incident-log.md | Dated postmortems behind the gotchas above — reproduction, root cause, exact fix location |
references/tmp-inline-sprites.md | TMP <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.md | Diagnosing 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.md | Hand-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.md | Frame 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.md | Verbatim full text of hard rules #22, #23, #25 (TMP outline serialization, TMP alignment pair, one font per Text) |
references/layout-qa-playbook.md | Measurable 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 |
Visual change notice
Section titled “Visual change notice”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:
ScreenCapturein Play mode pert1k-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.