What is a Canvas?
- Game Development course
- Intermediate
- Lesson 31/83
- 4 min
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.
Practice Print Canvas root and mode info
Assign "Canvas" to uiRoot and "ScreenSpaceOverlay" to mode. Print UI Root: Canvas | Mode: ScreenSpaceOverlay to the console.
Starter code
using System;
class Program
{
static void Main()
{
// uiRoot ve mode değerlerini tanımlayıp yazdır
}
}Sample solution
using System;
class Program
{
static void Main()
{
string uiRoot = "Canvas";
string mode = "ScreenSpaceOverlay";
Console.WriteLine("UI Root: " + uiRoot + " | Mode: " + mode);
}
}Expected output
UI Root: Canvas | Mode: ScreenSpaceOverlay
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 Correct answer
- Having at least three distinct AudioSources in the scene
Explanation: All UI elements require a Canvas as their drawing space and must reside within its sub-hierarchy.
2 Specify overlay render mode
canvas.renderMode = RenderMode.____;
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
Explanation: ScreenSpaceOverlay is chosen to render UI directly onto the topmost 2D screen layer.
3 Canvas concepts
| Term | Meaning |
|---|---|
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 |