How to add and position text on canvas in Unity
Unity's user interface (UI) allows you to add and position the text using a
Previously, Unity used a basic text system for UI. However, with advancements, a new text system called the TextMeshPro was introduced. TextMeshPro is a powerful and flexible solution for text rendering in Unity. It offers advanced text layout and markup options, improved performance, and better text visual customization capabilities.
How to add text
Given below are the steps on how to add, position, and change the text on canvas in Unity.
Create a Text - TextMeshPro
Right click in the Hierarchy window and click on UI > Text - TextMeshPro.
This will create a canvas GameObject in the scene with a child.
Position the text
Adjust the text object's position either by:
Move tool in the scene view
Transform component in the inspector pane
Edit the text
Navigate to the TextMeshPro component in the inspector pane
Edit the "Text" field with the desired content
Create a C# script
Create a new C# script
A sample C# script is given below.
using System.Collections;using System.Collections.Generic;using UnityEngine;using TMPro;public class Modify_text : MonoBehaviour{public TMP_Text canvasText;// Start is called before the first frame updatevoid Start(){canvasText.text = "Hi, it's me!";}}
Explanation
Lines 1–3: These lines make the necessary imports.
Line 4: It includes the TextMeshPro namespace to allow access to the TextMeshPro related classes and functions.
Line 6: A class is declared namedÂ
Modify_text. It inherits methods from the classÂMonoBehaviour, a base class in Unity for the scripts attached to the specific GameObjects.Line 8: It declares a public variable named
canvasTextwhich is of typeTMP_text. The variable holds a reference to the TextMeshPro text object which you can modify.Lines 10–13: The
Start()method is a callback method which is automatically invoked before the first frame update. It is generally used for initialization.CanvasText.textsets the text of the TextMeshPro object (referenced by theCanvasTextvariable).
Create a GameObject
Create an empty GameObject in the hierarchy tab.
Assign the C# script to the GameObject
Select the GameObject
Drag and drop the C# script in the inspector pane
Drag the TextMeshPro text from the hierarchy into the
Canvas_Textfield in theModify_textscript component.
Enter the game mode
Enter the game mode
Your text should show the content specified in the C# script
Demonstration
Free Resources