Dealing with TextMeshPro instead of TextMesh

I’ve been stuck for a couple of days with the simplest task instructor ben gave which was simply changing the text of the text mesh in the editor using our script.

The problem is. I couldn’t find any object called Text mesh so I it was what’s throwing me problems like “NullReferenceException” and more because this line
textMesh = GetComponentInChildren<TextMesh>();
simply couldn’t find a “TextMesh” since I am using “TextMeshPro”

Hence i tried using GetComponentInChildren<TextMeshPro>(); BUT this only gave me an error since it couldn’t find such a method.

I later found out that the Solution to this was simply to include this library
using TMPro;
to make searching for “TextMeshPro” available using
GetComponentInChildren<TextMeshPro>();

Now the reason why i created this article apart from helping whoever is stuck for the same reason is… Why am i even allowed to make unity search for TextMeshes if i can’t create a Text Mesh… or is there a way to Create a text mesh that i’m not aware of.?

ps. i’m using Unity 2019.4.3f1

You can search for any component in the children whether it exists or not. Down the line you will learn about the importance of null checking or using TryGetComponent (which doesn’t work on children).

Incidentally, you may have noticed that TextMeshPro does not work by default in the same way that TextMesh does. To achieve the same functionality you have to change the shader. I made a video about it:

2 Likes

This is absolutely marvelous, i’m saving this video in a playlist because it really eases out alot of the confusions i had when dealing with text mesh pro, specially a way to scale it in the editor because scaling it by hand was a huge mess xD. Thanks alot for this video :star_struck:

I’m not really sure what null checking means, i mean in my head it’s basically searching for something that’s not there (guessing based on name) but i don’t think how that would help so if you can tell me about it i’ll be really grateful ")

If the component you are searching for using GetComponent doesn’t exist, then the variable you assigned the search to will be null (which is the computer science word for empty). If you try to operate on a null variable then the NullReferenceException error is thrown.

So what you do is you check for null after your search. You can do so positively or negatively.

if(textMesh == null) return;
A command like this one bails on the whole method. It is called guarding.

if(textMesh) {
// Do Stuff
}
This is more of a gate keeper type thing. It means “if the textMesh exists, do stuff”. It would allow the rest of the method to work even if the textMesh object was null.

Which you use depends on how important the textMesh is to your method. If nothing works without it, then bail if its null. But if it is a small cog in the wheel, then use the second one to enclose its functionality (called encapsulation).

1 Like

Privacy & Terms