TextMeshProUGUI - Change of field in script not showing.

Hi,

I have struggled with this for too long, can someone please help and/or direct me.

Here is my script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;


public class GameController : MonoBehaviour {


    public TextMeshProUGUI scoreText;


    void Start()
    {
        scoreText = GetComponent<TextMeshProUGUI>() ?? gameObject.AddComponent<TextMeshProUGUI>();
        scoreText.text = "Score: ";
    }
   
}

Here are other details that might be important:

  • In my hierarchy I have “Main Camera and directional light” as per new project.
  • I have added a canvas (no changes)
  • I have added a textmeshpro text UI to the canvas. I have changed the text input box to “I see TEXT”, and yes I do see the text when I press play.
  • I have added a empty gameobject.
  • I added the above script to the gameobject,
  • I have dragged the textmeshpro text to “Score text” on the Gameobject that holds the script.

When I press play I would expect the “I see TEXT” to change to "Score: ". (I have debugged the code and the text does change, it just doesn’t display in game view)

The above doesn’t happen, what rookie mistake am I making?

In point (6) I am assuming that by dragging you mean assign the text component to the public scoreText field. Correct?

If that is the case, when you are using GetComponent or adding a new component, you are doing so on the empty game object that contains this script. At such point, your scoreText variable points to a newly added text component which is not the same as the one contained in the canvas.

Furthermore since this newly added text component is on the game object which is likely outside the canvas (not a child of the canvas) it will not render because object using a CanvasRenderer must be children of a canvas in order to render.

Since you have already assigned the text component to the public field scoreText, in Start() you do not need to do anything. scoreText should already contain a reference to the text object. In Start() you should only be setting the text as you are doing.

If you still have issues, please post an image of your scene hierarchy so we can see how it is setup and what components are on each of them.

1 Like

I removed - scoreText = GetComponent() ?? gameObject.AddComponent();

I cant believe it was that simple, thanks!