Home > Software engineering >  Changing TextMeshPro Text which is child of 2D Sprite via script in Unity
Changing TextMeshPro Text which is child of 2D Sprite via script in Unity

Time:05-28

I have a 2D square object sprite that has a child TextMeshPro object which stores a number.

Hierarchy in Unity:

enter image description here

Unity Scene:

enter image description here

I want to dynamically change the number in the TextMeshPro object via a script that is a component of the 2D square object. Below is the code I'm using.

'''

[SerializeField] private TextMeshProUGUI m_playerText;

// Start is called before the first frame update
void Start()
{
    m_playerText.text = "8";
}

'''

However I am getting the error "NullReferenceException: Object reference not set to an instance of an object"

Would appreciate any feedback to solve this.

CodePudding user response:

Use GetComponentInChildren<TextMeshProUGUI>() for solve the problem:

void Start()
{
    m_playerText = GetComponentInChildren<TextMeshProUGUI>();
    m_playerText.text = "some text...";
}

CodePudding user response:

Has it already been mention nullReferenceExpection it means object is not been initiated to do that try to ** drag and drop the text TMP to player script Component**.

  • Related