[RESOLVED] Counting Objects with a foreach not quite working - fundamentals question.

Hey guys

I have ended my day with a problem that I believe is just a fundamental lack of understanding. I have shown my code just so you get the idea. I know its a bit rubbish but you will get the idea what i’m trying to achieve.

    public void EnemyRosta_Get()
    {      
        roster = GameObject.FindGameObjectsWithTag("Enemy");
        int i = 0;                                  //counter in increment        

            foreach (Object Enemy in roster)
            {          //Loop through objects to get a count of how many
                i++;                                    //Increment loop
                Debug.Log("EMEMIES = " + (i));
                if (i == 0)
                {
                    Debug.Log("NO EMEMIES LEFT IN SCENE");    
                }
        } 
    }
    /* -----< ROSTER FUNCTIONALITY -END >----- */

Looping through the way I am doing I guess is fundamentally bad or wrong. However, my issue is that because I have to go into the foreach loop, my count never goes to 0 when there are no Enemies. Instead of just fudging this I thought I would ask your advice for the recommended way of looking at my scene for game objects with a ‘Enemy’ tag and getting a count back.

Thanks

Paul

You just want the number of enemies? Don’t loop at all

int i = enemies.Length;
1 Like

Yes. I had this fundamental misunderstanding also. I believed because the iterator was a thing its purpose was to you know, not iterate when the next cell is empty. To do that you’d need to write your own MoveNext method.

The stock foreach loop behaves just like a regular for() loop. It iterates over the whole array, empty indexes included. So this will always add. Just slap a null check in and move on- (if Enemy == null return break, then add ++i afterwards if you get past it)

You should use a for() loop, foreach isn’t primarily intended to be easier to read- it has this whole structure designed for other purposes hidden under it. I studied the hell out of it and I still would need to dig up references to mess with one properly.

1 Like

Works perfectly. Thanks very much. Another major fundamental thing learned.

    public void EnemyRosta_Get()
    {
        roster = GameObject.FindGameObjectsWithTag("Enemy");

        if (roster.Length == 0)
        {
            Debug.Log("NO EMEMIES LEFT IN SCENE");

        }   
    }
    /* -----< ROSTER FUNCTIONALITY -END >----- */

That’s the better solution, for sure. In case you were wondering why the original code didn’t work at all (rather than just being inefficient), you were doing your == 0 check inside a loop - but when there were actually no items in the list, that section of code would never be run. If you’d moved that check outside the foreach, it would’ve worked. (Just… slowly.)

2 Likes

Makes sense thanks StarManta.