GetComponent vs using object type

  • I was doing this: public GameObject text; and then I was using GetComponent from the Start method.
  • I figured out that I can do this: public TextMeshProUGUI text;.

Which is better and why?

The second approach is more useful, since with that one you have all the information you need. With the first, you have to keep calling GetComponent to get at the text. The second approach essentially requires only one GetComponent call, or none if you’re assigning it in the inspector.

If you only want the TextMeshProUGUI componente, then go for the second approach. That way it’s more clear why you want that variable and you don’t need to retrieve the component at startup.

Even if you’re going to want other components, there’s little reason not to use the second approach. You always still have the option of using GetComponent to find other components on the object and .gameObject to access the GameObject functionality (which is faster and more reliable than GetComponent).

The only reason to use GameObject as your referenced object is if your script has to work on objects that aren’t guaranteed to have any other components on them. In any other scenario, use the component that is known to be on the target object and/or the component you expect to use.