# How to loop through objects in class (XNA)? [closed]

In my game I have an Enemy class, and in that I have a constructor which I use to make Enemy objects.

How do I add all Enemy objects to a list or loop through all of them using a foreach loop?

I have tried various variations of this:

foreach(object E in Enemy){
//Do collision detection, set AIs next move, etc.
}


However, it always rejects the second part of the foreach loop, saying that Enemy is a type but is used as a variable.

The error you state is correct, 'Enemy' is a type. What you have there is equivalent to 'foreach (object E in integer)' or 'foreach (object E in string)'.

You need to add the enemy instances to a list or array. It should be roughly:

//Creating enemies
List<Enemy> enemyList = new List<Enemy>();

Enemy e = new Enemy();

etc...


then to iterate:

foreach (Enemy anEnemy in enemyList)
{
if (anEnemy.IsDoingWhatever)
etc...

}

• I take it there is no automatic way to add all enemys to enemyList? – James Gould Jan 5 '14 at 4:48
• There's no magical way, no. The simplest way might be to use a factory sort of pattern when you create them (an EnemyManager class or something like that). The 'Enemy' class is just another class... each enemy object just another object. – DrHeinous Jan 5 '14 at 5:04
• @JamesG You wouldn't want to do this. There are many scenarios where you want to have more than one list. So which list do they get added to? Best to make it explicit, as per the answer. – Andrew Russell Jan 5 '14 at 5:04