Week 2 — C#, Systems and the Coding Masterclass · w2d1 · 4h 01m

W2D1: UI, sprites and physics (part 1)

Canvas render modes, nine-slice sprites, anchors, canvas scaler, safe areas, and a first pass at Unity physics with rigidbody-driven movement.

Lucian Lazar · 15 Jul 2024

Week two opens with the biggest surface area in Unity that isn’t rendering: user interface. This is a long session — roughly four hours — covering canvases, images, text, anchors, mobile scaling, notches and scene transitions, then pivoting into the first half of physics by giving the platformer character a rigidbody and making it jump for real. It’s aimed at people who’ve followed week one and now want their game to have menus, buttons and a character that responds to forces instead of scripted position changes.

What’s covered

Canvas and render modes

  • Creating a canvas, why every UI element must live inside one
  • Screen Space Overlay (the default, always drawn on top of 3D), Screen Space Camera (canvas gets depth, so particle effects and 3D objects can sit in front of UI), and World Space
  • A demo of a world space canvas parented to a cube, rotated in 3D, with a working clickable button on its face
  • Why a 3D object dropped inside a canvas gets a RectTransform whether you wanted one or not

Buttons and TextMesh Pro

  • Why the button menu item says “TextMeshPro” — Unity acquired the asset and replaced their built-in text component with it
  • Wiring an OnClick handler in the inspector, dragging in a game object, picking the component and the method
  • The one-time TMP essentials import, and what the generated folder is for

Image vs Raw Image

  • Image takes a Sprite, Raw Image takes a raw texture — useful for render textures, webcam feeds and video
  • UV rect, wrap mode repeat, and tiling a texture inside a Raw Image
  • Raycast Target: turn it off on purely decorative elements. Unity walks every raycast-enabled element on every touch, so this is free performance
  • Raycast padding for making small buttons easier to hit with a thumb

Nine-slice

  • Installing the 2D Sprite package to get the Sprite Editor
  • Setting borders so corners stay fixed and the middle stretches, and what happens when you squash a sprite smaller than its corners
  • Lucian fumbles this live for a few minutes before getting it right, which is honestly more instructive than a clean take

RectTransform, pivots and anchors

  • Why UI uses RectTransform instead of Transform, and how position is measured from the pivot relative to the parent’s pivot
  • Pivot mode vs center mode in the scene toolbar, and how it behaves with multi-selection
  • Anchors as pins: anchors together means fixed size, anchors spread means the child stretches with the parent
  • Stretch-to-parent, anchoring to a corner, and why the child keeps constant padding from the anchor edges
  • His opinion, stated plainly: most people never understand anchors and end up piling on Content Size Fitters and layout groups to work around them

Mobile

  • Canvas Scaler: Constant Pixel Size, Constant Physical Size (for thumb-sized joystick buttons), and Scale With Screen Size with match set to height, which is what he’s used since 2016
  • Using a second canvas with a different scale mode for the elements that need physical sizing
  • The Device Simulator package, rotating devices, the safe area overlay
  • The Notch Solution asset and a Safe Padding component to keep UI out of the notch and gesture zones

Physics, part one

  • A free joystick asset driving a rigidbody’s velocity in FixedUpdate
  • Why physics work belongs in FixedUpdate (fixed timestep is 0.02s by default, independent of frame rate)
  • Setting velocity vs transform.Translate vs AddForce, and when you need Time.deltaTime and when you don’t
  • isKinematic and freeze-rotation constraints
  • Capsule collider and rigidbody on the player, plus a walk animation, isGrounded bool and walkSpeed float parameters, and animator transitions with exit time disabled

Timestamps

  • 00:13:00 — What week two covers, and a warning that Wednesday’s C# session will run four hours and is really a standalone programming course
  • 00:15:00 — Creating a canvas, the three render modes, why Overlay is the default
  • 00:22:00 — Screen Space Camera, plane distance, and putting a 3D cube in front of the UI
  • 00:27:00 — World Space canvas parented to a cube, with a working button on its face
  • 00:35:00 — Buttons, and the story behind TextMesh Pro replacing Unity’s built-in text
  • 00:42:00 — Writing ButtonBehavior, namespaces matching folders, wiring the OnClick handler in the inspector
  • 00:52:00 — Image vs Raw Image, UV rect, wrap mode repeat
  • 01:02:00 — Raycast Target as an optimisation, and raycast padding for small mobile buttons
  • 01:08:00 — Nine-slice: installing the 2D Sprite package, setting borders, and debugging it live
  • 01:22:00 — RectTransform, pivot mode, rotating and scaling around pivots
  • 01:30:00 — Anchors explained properly: pinning, stretching, and why the distance to the anchor centre stays constant
  • 01:45:00 — TextMesh Pro zoom quality vs the old rasterised text, and 3D TMP for name tags above characters
  • 02:00:00 — Canvas Scaler modes, reference resolution, match width vs height
  • 02:15:00 — Device Simulator package and the safe area overlay
  • 02:22:00 — Joystick asset, moving a cube by setting rigidbody velocity, FixedUpdate and the fixed timestep
  • 02:40:00 — velocity vs transform.Translate vs AddForce, isKinematic, and capping editor frame rate so your laptop fans stop screaming
  • 02:52:00 — Notch Solution asset and safe padding on a real device profile
  • 03:00:00 — Easy Transitions asset, scene loading, and why scenes must be added to Build Settings
  • 03:18:00 — Player capsule collider, rigidbody, freezing Z position and all rotations for a platformer
  • 03:28:00 — Walk animation, isGrounded and walkSpeed parameters, building transitions with no exit time
  • 03:40:00 — Full walkthrough of the player script: ground check, jump trigger, sprite flipping
  • 03:50:00 — Viewer question: why you can’t assign transform.localScale.x directly (value types vs reference types)

What you build

A UI scratch scene with canvases in all three render modes, a counting button, a tiled raw image, a nine-sliced progress bar, and anchor experiments. A mobile setup with a canvas scaler, a fixed joystick pushing a cube around via rigidbody velocity, and a safe-area-aware layout tested against real device profiles in the simulator. Then a scene transition between two scenes using a downloaded asset, and finally the week-one platformer character upgraded with a capsule collider, a rigidbody with constraints, a walk animation and a script that handles horizontal movement, grounded detection, jumping and sprite flipping.

The run animation is left as homework. It’s in the repo if you get stuck, but building it yourself is the point.

Code shown

The hello world for UI — a button that counts clicks:

public class ButtonBehavior : MonoBehaviour
{
    private int n;

    public void OnButtonPress()
    {
        n++;
        Debug.Log("button clicked " + n + " times");
    }
}
Moving a rigidbody from joystick input, in FixedUpdate, with no deltaTime because we're setting velocity rather than moving the object:

```csharp
private void FixedUpdate()
{
    target.velocity = new Vector3(
        joystick.Horizontal * moveSpeed,
        target.velocity.y,
        joystick.Vertical * moveSpeed);
}
## Who should watch this

If you finished week one and your scenes still have no menus, buttons or HUD, this is the session that fixes that. The anchors and canvas scaler segments are worth the price of admission on their own, especially if you've ever shipped a UI that looked fine in the editor and broke on a phone. The physics half is a soft introduction — velocity, constraints, FixedUpdate — with the heavier material saved for part two.

Part of the full curriculum. Course overview.