4

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.

RBT
  • 24,161
  • 21
  • 159
  • 240

2 Answers2

3

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

void Start()
{
    m_playerText = GetComponentInChildren<TextMeshProUGUI>();
    m_playerText.text = "some text...";
}
KiynL
  • 4,097
  • 2
  • 16
  • 34
0

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**.

  • Do you mean to drag and drop onto the inspector tab of the player object? – Abhishek Venkatesh May 28 '22 at 09:31
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 30 '22 at 08:21