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
EasyThe 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 publicTMP_Textfield namedzoneText. The scene links ZoneText to a field with that exact name. - Every frame, the text reads
Zone: Beachwhile the explorer's x is below 2, andZone: Junglefrom 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
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Building Real Games
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input Swap