harsha hirushan
harsha hirushan

Reputation: 141

how to get the TextMeshPro component

public class ClickBub : MonoBehaviour {
int x;
int count;
TextMeshPro mytext;
TextMeshPro soretext;
GameObject textobj;
// Use this for initialization
void Start () {
    textobj = this.gameObject.transform.GetChild (0).gameObject;
    mytext = textobj.GetComponent<TextMeshPro>();

in this mytext is a null value. how can i assign the TextMeshValue to the variable?

also says that unity engine can't convert type.

Upvotes: 11

Views: 37525

Answers (2)

Adel Kabboul
Adel Kabboul

Reputation: 171

Well, the thing is that the Text for TextMeshPro isn't a TextMeshPro Object, but rather a TMP_Text, So if you tried this :

TMP_Text mytext;
void Start () {
    mytext = textobj.GetComponent<TMP_Text>();
}

Now you should get a value in your mytext object.

Upvotes: 15

Basile Perrenoud
Basile Perrenoud

Reputation: 4112

When you do

textobj.GetComponent<TextMeshPro>();

Unity will look for the TextMeshPro component in the object textobj. According to your code, textobj is the first child of the object that has the ClickBub script. You should first check that this first child has a TextMeshPro component in your editor. To be sure that you access the elements you expect, you can try to print their names:

void Start () 
{
    textobj = this.gameObject.transform.GetChild (0).gameObject;
    Debug.Log(textobj.name);
}

Is it the object you expected?

Then if everything is setup properly but you want to add the TextMeshPro component if it doesn't have it, you can do

void Start () 
{
    textobj = this.gameObject.transform.GetChild (0).gameObject;
    mytext = textobj.GetComponent<TextMeshPro>();
    if(mytext == null)
    {
        mytext = textobj.AddComponent<TextMeshPro>();
    }
}

Upvotes: 3

Related Questions