0
0
Unityframework~5 mins

Canvas and render modes in Unity

Choose your learning style9 modes available
Introduction

Canvas is where you draw your user interface in Unity. Render modes decide how and where this drawing happens.

When you want to show buttons or menus on the screen.
When you need UI elements to stay fixed on the screen no matter where the camera moves.
When you want UI to appear as part of the 3D world, like labels above characters.
When you want to optimize performance by choosing the right way to draw UI.
Syntax
Unity
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
canvas.renderMode = RenderMode.ScreenSpaceCamera;
canvas.renderMode = RenderMode.WorldSpace;

RenderMode is a property of the Canvas component.

There are three main render modes: Screen Space - Overlay, Screen Space - Camera, and World Space.

Examples
This mode draws UI directly on the screen, always on top.
Unity
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
This mode draws UI using a camera, so UI can be affected by camera effects.
Unity
canvas.renderMode = RenderMode.ScreenSpaceCamera;
canvas.worldCamera = Camera.main;
This mode places UI in the 3D world, so it moves and rotates like other objects.
Unity
canvas.renderMode = RenderMode.WorldSpace;
canvas.transform.position = new Vector3(0, 1, 0);
Sample Program

This program changes the canvas render mode every 2 seconds and prints the current mode to the console. It shows how to switch between the three modes.

Unity
using UnityEngine;

public class CanvasRenderModeExample : MonoBehaviour
{
    public Canvas canvas;

    void Start()
    {
        // Set canvas to Screen Space Overlay
        canvas.renderMode = RenderMode.ScreenSpaceOverlay;
        Debug.Log("Render mode set to ScreenSpaceOverlay");

        // Wait 2 seconds then switch to Screen Space Camera
        Invoke(nameof(SetScreenSpaceCamera), 2f);
    }

    void SetScreenSpaceCamera()
    {
        canvas.renderMode = RenderMode.ScreenSpaceCamera;
        canvas.worldCamera = Camera.main;
        Debug.Log("Render mode set to ScreenSpaceCamera");

        // Wait 2 seconds then switch to World Space
        Invoke(nameof(SetWorldSpace), 2f);
    }

    void SetWorldSpace()
    {
        canvas.renderMode = RenderMode.WorldSpace;
        canvas.transform.position = new Vector3(0, 1, 0);
        Debug.Log("Render mode set to WorldSpace at position (0,1,0)");
    }
}
OutputSuccess
Important Notes

Screen Space Overlay is the simplest and fastest mode for UI that stays on screen.

Screen Space Camera lets UI react to camera effects like depth and perspective.

World Space mode is useful for UI that should exist inside the 3D game world.

Summary

Canvas is where UI elements are drawn in Unity.

Render modes control how and where the UI appears.

Choose the render mode based on whether UI should be fixed on screen or part of the 3D world.