GameObject.FindObjectsWithTag on empty array

Hey

I was wondering why the following will give me an exception if arr is empty

GameObject[] arr = GameObject.FindObjectsWithTag("xy");
foreach(GameObject go in arr) { ... }

Where is the problem with foreach in an empty array? The solution I have is to use a try-catch where catch is empty but this seems to wrong for such an often used functionality.

Am I missing something? There is no such problem in Java

foreach doesn’t cause problems when the array is empty but when it is null.

So if it’s empty, the foreach will run 0 times.
If it’s null, then that’s an error because you’re trying to iterate over something that doesn’t exist yet.
Being empty is different from being null.

Then why does FindObjectsWithTag return null instead of an empty array? Is try-catch the way to handle this? That would be bad design

Simply check is the array is null before executing the foreach.

1 Like

it’s not working:

GameObject[] arr = GameObject.FindGameObjectsWithTag("Opponent");
        if(arr != null) { ... }

result: UnityException: Tag: Opponent is not defined!

thats not a problem with the null check, that’s a problem with “didn’t setup the tag in the unity ide”

2 Likes

???

Yes, because there is nothing with the Opponent tag. Because there will be some levels where there is no GO with this tag.

If I search for a single GO, then I wont get a “ShitWasntFoundException” but the GO is just null which I can check for.

You still need to pre-configure all the possible tags at compile time. The error is saying the tag doesn’t exist, not that it couldn’t find any GameObjects with the tag.

But this tag itself exists. This scene I enter doesn’t contain any objects of that tag. And afaik tags are not bound to scenes but to projects

I can’t believe nobody ever noticed this behavior :hushed:

Have you spelled it correctly? As in, is the tag named exactly “Opponent”, or is it “opponent” or “Oponent”?

yup
Using Unity 4 btw, maybe they fixed that in 5?