Unity Tutorial: Changing Text Colors Through Scripting

In this tutorial, we’ll explore the straightforward methods to change TextMeshPro text colors in Unity via scripting. Whether you’re looking to highlight important information, indicate status changes, or simply add visual flair to your game’s UI, these techniques will help you implement color changes efficiently in your Unity project.

For a visual breakdown of this subject, you may find my video discussion helpful.




Initial Setup

Text Mesh PRO Text Component

When using TextMeshPro, you’ll likely work with one of the two component types shown in the images below: either a TextMeshPro – Text (UI) component that displays on your user interface (which must be placed inside a Canvas), or a TextMeshPro component that renders in world space like a 3D model. Fortunately, the color-changing method we’ll cover works effectively for both component types.

Creating a new TextMeshPro – Text (User Interface) component through the Unity hierarchy menu.
Creating a new TextMeshPro – Text (World Space) component through the Unity hierarchy menu.



Second step – Choose one of your scripts or create a script and assign it to a GameObject from the scene

For changing color text in Unity at runtime, create a script that executes when your game runs. Add ‘using TMPro;’ at the top to import the TextMeshPro namespace, then declare a TMP_Text variable before your Start function—for example, ‘public TMP_Text myText;’ (though you can choose any variable name). This steps are shown below.

After attaching your script to a GameObject, you’ll notice your variable appears in the Inspector but shows ‘None’ in the field. To proceed with changing color text in Unity, you need to initialize this variable. Simply drag the TextMeshPro component you want to modify into the field in the Inspector, as demonstrated in the images below.

With your variable initialized, you can now change text color in Unity through your script by accessing the color parameter with the dot operator. Add ‘myText.color = Color.yourChosenColor;’ in the Start method, and when you press Play, you’ll see the text immediately display in your new color, as illustrated in the images below.



For more flexibility, define a public Color variable in your script, which will allow you to select your preferred text color directly through the Unity Inspector, as demonstrated in the images below.

Scroll to Top
Secured By miniOrange