In GameStatus.cs, would it be ok to follow the "cached reference" method?

public class GameStatus : MonoBehaviour
{
    // config params
    [Range(0.1f, 10f)] [SerializeField] float gameSpeed = 1f;
    [SerializeField] int pointsPerBlockDestroyed = 1;

    // cached reference
    TextMeshProUGUI textMeshProUGUI;

    // state var
    [SerializeField] int currentScore = 0;

    private void Start()
    {
        textMeshProUGUI = FindObjectOfType<TextMeshProUGUI>();
    }

    private void Update()
    {
        Time.timeScale = gameSpeed;
        textMeshProUGUI.text = currentScore.ToString();
    }

    public void AddToScore()
    {
        currentScore += pointsPerBlockDestroyed;
    }
}

The code works fine, but it is quite different to the answer in the course video shown.
I wonder if it works just for the current stage, but get different errors later on…

Hi,

FindObjectOfType returns the first object it finds, whatever Unity defines as “first”. If you have only one TextMeshProUGUI object in your scene, your approach is perfectly fine. :slight_smile:


See also:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms