How does Unity know which GetComponent<> or FindObjectOfType<> to return?

Perhaps I’m getting ahead of myself here, but I’m a little confused by the behavior of using GetComponent<> and FindObjectOfType<>.

In this lesson, for example, we call FindObjectOfType<StarDisplay>().AddStars(), but what if our Scene contains more than on StarDisplay object? How does Unity know which one we want?

This is even more confusing to me when using GetComponent<>. We could have multiple Text components on a single Canvas, for example. If we just call GetComponent<Text>, which one is returned?

Again, this might be explained further in future lessons, but I’d like to understand how Unity works in these cases.

Hi,

In this lesson, for example, we call FindObjectOfType<StarDisplay>().AddStars() , but what if our Scene contains more than on StarDisplay object? How does Unity know which one we want?

That’s the problem. It doesn’t. It returns the “first” object it finds, whatever it defines as “first”. If you have two StarDisplay objects in your scene and require a specific object, FindObjectOfType could cause a problem.

The same applies to GetComponent if you have more than one object attached to the same game object, and you need a specific component/object.

Unity’s Find methods and GetComponent method are suitable if you have only one object of the type you are looking for in your scene and attached to the same game object respectively, or if you do not need to distinguish between objects.

Is this what you wanted to know?

Yes, that answers my question exactly.

I’m not sure I can think of a reason to have two of the same Component type on a GameObject, but I wanted to understand this limitation before that happens and I end up with some confusing bugs.

Thank you.

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

Privacy & Terms