FindObjectOfType for multiple Objects

Hello,

I was watching this section and Rick uses FindObjectOfType. I was wondering if you can use it when there are multiple objects of the same type, like the blocks for example.

Thank you.

Hi,

FindObjectOfType returns the first object it finds, whatever Unity defines as “first”. If you are looking for a specific Bliok object, FindObjectOfType might return the “wrong” object.

Is this what you wanted to know?


See also:

Gotcha!

So this isn’t useful in a situation like that, where I would want a specific instance of a repeated object? Is there something that would be more appropriate for that kind of thing?

I’m not sure if you are referring to the FindObjectOfType method or the specific instance but if you are referring to the latter, you could, for example, use [SerializeField]. If you know the game object, GetComponent could work.

However, it is relatively unlikely that you spawn x enemies of the same type during runtime and want to access a specific one “out of the blue”. And if you spawn something during runtime, you could easily add each spawned game object to a list and filter that list for a specific object.

Bear in mind, though: If you are not able to distinguish between all those objects at all, you will not be able to do that via code and/or in Unity either. You always need some kind of a filter criterion, just like in the real world.

1 Like

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

Privacy & Terms