FindObjectOfType method when there are more than 1 objects of the same type

In “Updating UI Text to Show Score” lecture, we learned that we can get object in the scene by FindObjectOfType<>() method. Out of curiosity, what if there are two objects of the same type? From the manual, it seems like it will return an array of the same type. In that case, how do you determine which object is the one you want? Do you look into their name field or some other fields?

1 Like

Hi @dcwang,

Yep, you certainly can.

You could iterate through the array, and then, based on the other properties (name, tag etc) effectively filter some out.

If you look at the second link below, you’ll see that this specifically states that it will return an Object array (Object[]) whereas the first link doesn’t specify it will, I suspect under the Unity hood it’s using the other method if more than one object of the same type is found.

The second link provides a nice example of iterate through, and of casting the returned Object to the type that you were looking for.

Hope this helps :slight_smile:


See also;

1 Like

Got it, Rob. Thanks for the help!

1 Like

You’re very welcome :slight_smile:

Privacy & Terms