Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 36 ยท UI and Input

UI Canvas and Layout in Unity

Learn the Unity UI (uGUI) basics - Canvas render modes, Canvas Scaler, RectTransform anchors and pivots, layout groups and safe areas - with runnable math stand-ins.

Every menu, health bar and score counter in a Unity game lives on a Canvas. The Canvas is a special game object that draws its children as 2D user interface on top of (or inside) your scene. Getting the Canvas, the Canvas Scaler and the anchors right is what makes a UI look correct on a phone, a 4K monitor and everything in between.

This lesson covers the classic Unity UI system, called uGUI (the UnityEngine.UI package). You will learn the three render modes, how scaling works, how a RectTransform positions an element, and how layout groups arrange children for you. Unity itself is not available on this site, so the C# you can run here are small plain C# stand-ins that reproduce the math; the Unity API snippets are read-only.

Creating a Canvas

In the editor choose GameObject > UI > Canvas. Unity creates three things: the Canvas, an EventSystem (which routes clicks, touches and keyboard input to UI elements) and nothing else. Every UI element must be a descendant of a Canvas; elements placed elsewhere never render.

A Canvas has a Render Mode:

  • Screen Space - Overlay: drawn on top of everything, always matches the screen. The default and the cheapest choice for menus and HUDs.
  • Screen Space - Camera: drawn at a distance in front of a chosen camera. Use it when post-processing, particles or perspective effects must affect the UI.
  • World Space: the Canvas is an object in the scene with its own position, rotation and scale. Use it for in-world screens, name tags above characters and VR menus.
flowchart LR
  A["Canvas"] --> B["Screen Space - Overlay<br/>on top of the screen"]
  A --> C["Screen Space - Camera<br/>in front of one camera"]
  A --> D["World Space<br/>an object in the scene"]

Three render modes: pick Overlay unless you need the UI to be part of the 3D world.

Canvas Scaler: one design, many screens

Screens have different sizes. If you place a button at pixel 1000 on a 1920-wide screen, it falls off a 1280-wide one. The Canvas Scaler component fixes this. Set UI Scale Mode to Scale With Screen Size, choose a Reference Resolution (for example 1920x1080) and a Match value between 0 (match width) and 1 (match height).

The scaler computes one scale factor. With the Match Width Or Height mode it blends the width and height ratios on a logarithmic scale:

C#
// read-only: the factor Unity uses, written out
float logWidth  = Mathf.Log(Screen.width  / referenceWidth,  2);
float logHeight = Mathf.Log(Screen.height / referenceHeight, 2);
float scale = Mathf.Pow(2, Mathf.Lerp(logWidth, logHeight, match));

A landscape game usually uses match 0.5. A portrait phone game often matches width (0) so the UI never gets wider than the screen.

C# Stand-in: Canvas Scaler factor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice how the portrait phone (1080x1920) shrinks to 0.56 with match 0 but would be 1.78 with match 1. The right choice depends on which direction your layout can stretch.

RectTransform: anchors, pivot and offsets

UI elements use a RectTransform instead of a plain Transform. Four ideas matter:

  • Anchors are two points (min and max) in the parent's rectangle, each given as a fraction from 0 to 1. When the parent resizes, the anchors move with it.
  • Offsets (offsetMin, offsetMax) are the distances in pixels from the anchors to the element's corners. With a single anchor point you see "Pos X / Pos Y / Width / Height" instead.
  • Pivot is the element's own origin (0,0 bottom-left, 0.5,0.5 centre). Rotation and scaling happen around the pivot.
  • Anchor presets (the square in the Inspector, hold Alt to also set pivot and position) cover the common cases: top-left corner, stretch across the bottom, fill the parent.
C# Stand-in: where does a RectTransform end up?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The bar changes width with the screen because its anchors are stretched; the button keeps its 200x60 size because both anchors sit on the same point.

Layout groups and fitters

Hand-positioning a list of items is tedious. Add a Horizontal Layout Group, Vertical Layout Group or Grid Layout Group to a parent and it arranges its children automatically. Useful settings are Padding, Spacing, Child Alignment and Control Child Size / Child Force Expand. A Content Size Fitter resizes the parent to fit its children (or a text), and a Layout Element on a child sets minimum, preferred and flexible sizes. A Scroll View wraps a long layout in a scrollable viewport.

Remember: layout groups take control of the children's position and size, so you cannot drag those children by hand while the group is active.

Safe areas and sorting

Phones have notches and rounded corners. Screen.safeArea returns the usable rectangle in pixels. A common pattern is a script on a full-screen panel that converts it into anchors:

C#
using UnityEngine;

[RequireComponent(typeof(RectTransform))]
public class SafeAreaPanel : MonoBehaviour
{
    void Start()
    {
        var rt = (RectTransform)transform;
        Rect safe = Screen.safeArea;
        rt.anchorMin = new Vector2(safe.xMin / Screen.width, safe.yMin / Screen.height);
        rt.anchorMax = new Vector2(safe.xMax / Screen.width, safe.yMax / Screen.height);
        rt.offsetMin = rt.offsetMax = Vector2.zero;
    }
}

Drawing order inside one Canvas follows the Hierarchy: later siblings draw on top. Between Canvases, Sort Order decides. Use a few Canvases (for example a static HUD and a frequently changing one), because a Canvas rebuilds its mesh when anything inside it changes; see Profiler and optimization.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which Canvas render mode should you pick for a normal menu or HUD?

    Overlay always fills the screen and is the cheapest mode; use Camera or World Space only when the UI must be affected by a camera or live in the scene.
  2. 2. What does the Canvas Scaler's Reference Resolution describe?

    The scaler compares the real screen to the reference resolution and scales the whole Canvas accordingly.
  3. 3. A button has both anchors on the same point. What happens when the parent grows wider?

    With a single anchor point the element has a fixed width and height; only its position follows the anchor.
  4. 4. Why can't you drag a child of a Vertical Layout Group by hand?

    The group recalculates positions whenever the layout changes, so manual positions are overwritten.

Summary

  • Every uGUI element sits under a Canvas; the EventSystem delivers input to it.
  • Overlay, Camera and World Space are the three render modes; Overlay is the default.
  • Canvas Scaler with Scale With Screen Size keeps one design usable on all screens.
  • RectTransform = anchors + offsets + pivot; stretched anchors resize, single-point anchors keep their size.
  • Layout groups, fitters and Scroll Views arrange content automatically; use Screen.safeArea for notches.

Next: Buttons, Text and UI Events