Unity - Text Element



Unity’s inbuilt text UI is a great starting point for learners to get into designing UI, even if it tends to be overshadowed by more powerful and efficient community-built assets.

For our purpose, the vanilla Text element is more than sufficient to get started.

Text being a distinct UI element of its own is primarily due to the dynamism of that element. For example, printing the player’s current score to the screen requires the numeric value of the score to be converted to a string, generally through the .toString() method, before it is displayed.

To insert a Text UI element, go to the Scene Heirarchy, Create → UI → Text.

Create UI Text

A new Text element should show up in your Canvas region. If we have a look at its properties, we will see some very useful options.

Text element

What is most significant of all, however, is the Text field. You can type out what you want the text box to say in that field, but we want to go a step further than that.

To change the font of the text, you must first import the font file from your computer into Unity, as an Asset. A font does not need to be actively attached to anything in the scene, and it can be directly referenced from the Assets.

The Text element can be accessed through scripting as well; this is where the importance of dynamic UI comes in.

Instead of the console, outputting how many times the button has been pressed, as in the previous chapter; let us actually print it out on the game screen. To do so, we will open up our ButtonBehaviour script from the previous lesson, and make a few changes to it.

using UnityEngine;
using UnityEngine.UI;
public class ButtonBehaviour : MonoBehaviour {
   int n;
   public Text myText;
   public void OnButtonPress(){
      n++;
      myText.text = "Button clicked " + n + " times.";
   }
}

The first change we did was to add a new namespace reference. This reference is used to work with Unity’s UI components, and so we add the using UnityEngine.UI line.

Next, we create a public Text variable, where we can drag and drop our Text UI element onto.

Finally, we access the actual text this UI element contains using myText.text.

myText.text

If we save our script, we will now see a new slot for the Text UI element in our ButtonManager. Simply drag and drop the gameObject containing that Text element onto the slot, and hit the Play button.

New Slot Text UI Element
Advertisements