Game Development
What is a Canvas?
Learn that the Canvas is the root container for all UI elements.
What is a Canvas?
The Canvas is the foundational root container upon which all user interface (UI) elements (buttons, texts, images) are rendered in Unity. Every UI element drawn in a scene must strictly exist as a child of a Canvas in the hierarchy.
// Accessing Canvas component and render mode
Canvas canvas = GetComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
Without a Canvas present in the scene, UI components cannot be rendered to screen or receive player interactions.
Canvas Render Mode types
Canvas supports three primary render modes: Screen Space - Overlay (draws directly over screen as 2D), Screen Space - Camera (projects in front of a camera), and World Space (positions inside 3D space).
// World Space mode for over-character health bars
canvas.renderMode = RenderMode.WorldSpace;
Floating name tags or overhead enemy health bars typically use World Space to reside at 3D world coordinates.
Exercise Print Canvas root and mode info
Assign "Canvas" to uiRoot and "ScreenSpaceOverlay" to mode. Print UI Root: Canvas | Mode: ScreenSpaceOverlay to the console.
Show example solution
using System;
class Program
{
static void Main()
{
string uiRoot = "Canvas";
string mode = "ScreenSpaceOverlay";
Console.WriteLine("UI Root: " + uiRoot + " | Mode: " + mode);
}
}
Test yourself
-
What is the prerequisite rule for UI elements like buttons, texts, and health bars to render on screen in Unity?
- Objects containing a MeshRenderer material
- Objects having a Rigidbody component
- Objects residing beneath a Canvas in the hierarchy
- Having at least three distinct AudioSources in the scene
Show answer
Objects residing beneath a Canvas in the hierarchy — All UI elements require a Canvas as their drawing space and must reside within its sub-hierarchy.
-
Specify overlay render mode
canvas.renderMode = RenderMode.____;
Show answer
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
-
Canvas concepts
- Canvas
- Core root holding all UI elements
- Screen Space - Overlay
- Renders UI directly on top screen layer
- World Space
- Renders UI as object in 3D world
- EventSystem
- Passes user inputs to UI
Next lesson: Text and TMP