Menu
CoddyTech

Canvas and Text

Part of the Building Real Games section of Coddy's Unity journey. Lesson 1 of 56.

Unity draws on-screen text, buttons and bars with its UI system. In Unity 6, GameObject > UI > Text - TextMeshPro adds a text object named Text (TMP); the first time, Unity asks to import the TMP Essentials, which the text needs for its font. If the scene has no Canvas yet, Unity makes one and puts the text inside it, plus an EventSystem that UI clicks go through. The Canvas draws its children over the camera's picture, at a fixed place on the screen wherever the camera looks. Set its Canvas Scaler to Scale With Screen Size, 1920 x 1080, Match 0.5, as every scene in this course does, and the layout keeps its proportions on any screen size.

The text's component is TextMeshPro - Text (UI). Scripts hold it in a field of its base type TMP_Text, from the TMPro namespace, and change what it shows through its text property, a string. This script names the level when it starts:

using UnityEngine;
using TMPro;

public class LevelIntro : MonoBehaviour
{
    public TMP_Text titleText;

    void Start()
    {
        titleText.text = "World 2: Ice Caves";
    }
}

Drag the Text (TMP) object from the Hierarchy into the Title Text slot in the Inspector, and Unity puts its text component in the field. Without using TMPro; the name TMP_Text is unknown and the script does not compile (CS0246). With the slot left empty, the first titleText.text throws UnassignedReferenceException. What the script writes replaces the Text Input typed in the Inspector, which is New Text on a fresh text.

challenge icon

Challenge

Easy

The explorer walks the island with the left and right arrows, as Explorer.cs already does. Show where it is in the ZoneText at the top of the screen, which still reads New Text:

  • Add using TMPro; and a public TMP_Text field named zoneText. The scene links ZoneText to a field with that exact name.
  • Every frame, the text reads Zone: Beach while the explorer's x is below 2, and Zone: Jungle from 2 on.

Press Play, walk onto the grass and back, then Check.

Try it yourself

using UnityEngine;

public class Explorer : MonoBehaviour
{
    public float speed = 4f;

    void Update()
    {
        float move = Input.GetAxisRaw("Horizontal");
        transform.Translate(move * speed * Time.deltaTime, 0f, 0f);

        // Show the zone in the ZoneText: Zone: Beach below x = 2, Zone: Jungle from 2 on
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Building Real Games