TextMeshProUGUI issues when trying to change text during gameplay.

I’m using GetComponentInChildren for 2 different TextMeshProUGUI but as soon as I try to play it changes both into the same one. What I’m trying to make is a script to show both time and score.

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

public class Scores : MonoBehaviour
{ 
  
    public TextMeshProUGUI TimeCounter;
    public TextMeshProUGUI ScoreCounter;

    void Awake(){
        TimeCounter=GetComponentInChildren<TextMeshProUGUI>();
        ScoreCounter=GetComponentInChildren<TextMeshProUGUI>();
    }

    public void TheTime(float H){
    
        TimeCounter.text=H.ToString();
    }
    public void TheScore(int P){
        ScoreCounter.text="Score: "+P;
    }
}

Any hints? I was getting NullReferenceException when trying to change their texts with GetComponent instead of GetComponentInChildren.

GetComponentInChildren() returns the component of the first child it finds. Your script is looking through the hierarchy and it’s returning the TextMeshProUGUI component of only the first child that has it.

GetComponent() didn’t work because it’s looking for components on the actual object that your script is attached to. My guess is that you are dragging this script onto an object that doesn’t have a TextMeshProUGUI component, therefore GetComponent() returns null.

What I would do:
Simply delete everything in the Awake().
Place this script on any object in your scene.
Drag and drop the TextMeshProUGUI component that you are looking for into the fields in the inspector.

1 Like