Unity how to add text

Unity: How to Add Text to Your Project

When first delving into Unity, newcomers may find themselves wondering how to incorporate text effectively into their projects. The question becomes, should one go for the classic Text component or opt for TextMeshPro? This guide aims to shed light on this matter.

TextMeshPro: The Superior Choice

Since Unity 2019, TextMeshPro comes pre-installed, and it is highly recommended to use this text solution and abstain from the classic version. TextMeshPro offers a myriad of additional functionalities and excels in rendering text quality.

When using TextMeshPro, all it takes is adding the first component. A pop-up will appear, prompting you to click “Import TMP Essentials”, and you’re all set to utilize it.

Unity how do add text, install TextMeshPro essentials

How to Add Text in a UI (User Interface) Space

To add text in a UI context, follow these steps:

  1. Right-click on your scene hierarchy.
  2. Go to UI -> Text – TextMeshPro.”
  3. Alternatively, use the top menu: “GameObject -> UI -> Text – TextMeshPro.”

Unity how to add text in UI

If your scene lacks a canvas, Unity will create one automatically for you (by default in Screen-Space Overlay mode, ensuring it appears in front of your 3D world). Your text will become a child of this canvas. You can then customize your text and position it as needed. Just bear in mind that position coordinates are now screen coordinates.

How to Add Text in a 3D World

For adding text within a 3D environment, proceed as follows:

  1. Right-click on your scene hierarchy.
  2. Go to “3D Object -> Text – TextMeshPro.”
  3. Alternatively, use the top menu: “GameObject -> 3D Object -> Text – TextMeshPro.”

Unity how to add text in 3d

Similar to the UI section, you can customize your text and position it as needed, but this time, the coordinates are genuine 3D coordinates.

How to Add Text in Code

If you prefer to add text dynamically through scripting, you can use the following code examples. However, in situations where your game is running, it may be more practical to create prefabs rather than adding text through code.

For UI Environments:

using UnityEngine;
using TMPro;

public class AddTextUI : MonoBehaviour
{
    private void Start()
    {
        gameObject.AddComponent<TextMeshProUGUI>();
    }
}

For 3D Environments:

using UnityEngine;
using TMPro;

public class AddText3D : MonoBehaviour
{
    private void Start()
    {
        gameObject.AddComponent<TextMeshPro>();
    }
}

These scripts allow you to add TextMeshPro components in either a UI or 3D context. Remember to ensure that your UI game objects are children of a canvas when working in a UI environment.

Once you’ve added text, you can also edit it and change the color of your text.

Happy coding !

Leave a Reply

Your email address will not be published. Required fields are marked *