Update multiple text scores on screen with one script

I have multiple texts on screen that need updating. All have their own individual script for updating themselves. I would like to use one script that would update all this text. However, when I try to merge these scripts into one, it seems the fields share information.

One thought was to check which text item the script is attached to then, only update that text. Here is my code:

public class ScoreDisplay : MonoBehaviour
{
    TextMeshProUGUI _scoreText;
    TextMeshProUGUI _highScoreText;
    GameSession _gameSession;
    int _highScore;

    private void Start()
    {
        _scoreText = GetComponent<TextMeshProUGUI>();
        _highScoreText = GetComponent<TextMeshProUGUI>();
        _highScore = PlayerPrefs.GetInt("HIGH SCORE", 0);
        _gameSession = FindObjectOfType<GameSession>();
    }

    private void Update()
    {
        _scoreText.text = _gameSession.GetScore().ToString();
        _highScoreText.text = _highScore.ToString();
    }

What is your question? Or could you please be more descriptive of the problem you are trying to solve? Also, when pasting code to the forum, there is a </> button in the post editor that can be used to post preformatted text.

–

Ok Thanks dstears. Currently, for all numeric updates like score, shields, energy etc. Each of these has its own separate script that updates these values. In my code snippit above, if I comment out anything that has to do with highscore, then the current score will update as it should. I then need basically the same script and attach it to the highscore text on the game screen. Same with energy or shields. Each have their own script. I'd like to be able to update all these in one script, like a HUD manager type script.

–

1 Answer

1

In Start(), you’re assigning the same value to _scoreText and _highScoreText.
From the doc for GameObject.GetComponent :

GetComponent returns only the first matching component found on the GameObject on which it is called.

So even if you have 2 TextMeshProUGUI the first one will be assigned to both fields.

I see 2 ways to solve that:

  • You could use [SerializedField] and assign your values in the editor.
  • If you want to avoid that, I guess you could have your TextMeshProUGUIs in childrens of your manager to differentiate them. Then you can either get them by name or use [SerializedField].

Sorry if this wasn’t clear.
Good luck!

Thanks PaulMDev. I will try serializing the field and see how that goes.

–