Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing TextMeshPro Text which is child of 2D Sprite via script in Unity

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.

like image 506
Abhishek Venkatesh Avatar asked Oct 20 '25 03:10

Abhishek Venkatesh


1 Answers

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

void Start()
{
    m_playerText = GetComponentInChildren<TextMeshProUGUI>();
    m_playerText.text = "some text...";
}
like image 189
KiynL Avatar answered Oct 21 '25 17:10

KiynL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!