Trying to instantiate a text above enemy... code works but text not showing

So guys, I am trying to reproduce an effect from a game where when an enemy gets hit, the damage pops up above them for just a brief second. I made a text mesh pro text box, made it a prefab and made a script that takes this prefab ( the enemy script ) …
When I take damage, I instantiate the TMPUI right above the enemy with the damage … this all seems to work. From the SS below, you can see in the Hierarchy that I am getting TMP clones and if you look at the scene view you will see them above enemies… but in game, you never see the text.
If I pause and inspect these clones they even have the damage set as their text value. Any ideas?

private void ShowDamageText(int damage)
    {
        Vector3 damageTextPosition = transform.position + new Vector3(0f, 1.5f, 0f); // Adjust the Y value as needed
        TextMeshProUGUI damageText = Instantiate(damageTextPrefab, damageTextPosition, Quaternion.identity);
        damageText.text = damage.ToString();
        Destroy(damageText.gameObject, 5.0f); //made it 5 seconds just to see if I could see it...
    }

I think it’s because they are not in a canvas. There are 2 TextMeshPro versions of text, and I believe the ones you are using require a canvas. When you right-click in the hierarchy to add a game object, you will find - under the 3D Object bits - an option to add Text - TextMeshPro.

Yours
image

3D Object
image

In code this is not TextMeshProUGUI but TMPro_Text. Afaik, this version does not need a canvas. If you still want to use the version you have, you would have to wrap each of your text fields in a world space canvas - fortunately you have a prefab. The size (yours is huge) will change dramatically.

1 Like

YES! This was my problem! Thanks so much! It’s actually TMP_Text in code but yes you were exactly right, thanks a ton!

1 Like

My bad, I was pulling from memory. Glad it helped, though

1 Like

no bad at all… you saved me from pulling my hair out.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms