SerializeField vs FindObjectofType

Hello,

just a quick question about the lecture. Why are we using [SerializeField] to connect the score text object manually with the Game Status Script? It work, but wouldnt this require us to connect the text object for every scene manually? At least it seemed to work that way for me. I tried out a workaround using FindObjectOfType<TextMeshProUGUI>() and it worked for all scenes without needing to adjust it further. Any particular reason we are not using that function here?

Thank you!

Alex

Hi Alekir,

Sometime concepts are introduced during the course just to make you familiar with them, not necessarily because they are the best choice for the given scenario. That said, with the above, if you were to manually add the reference to the text GameObject and then create that as a prefab, you wouldn’t need to perform that manual task in each scene, you could just drag in your prefab and you’re done.

Any of the Find methods have a cost associated with them. They have to traverse the entire scene, iterating through all of the GameObjects looking for the one you are specifying by type, name, tag etc. Where ever possible it is advisable to limit the amount of Find calls you make, and GetComponent to some degree too, although this isn’t quite so bad.

Well done for having a go at finding (excuse the pun) a different solution. :slight_smile:

I’m a bit late to the party, but it still might worth mentioning that FindObjectOfType<TextMeshProUGUI>() returns the first active loaded object of Type TextMeshProUGUI. If you have other objects of that type in your scene (one that displays the elapsed time, for example), the result may not be what you expected. Explicitly connecting the score text is more robust.

1 Like

Privacy & Terms