I have a 2D square object sprite that has a child TextMeshPro object which stores a number.
Hierarchy in Unity:
Unity Scene:
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**.