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.
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.