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.


closed as off-topic by concept3d, Josh Jan 5 '14 at 19:07

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Programming questions that aren't specific to game development are off-topic here, but can be asked on Stack Overflow. A good rule of thumb is to ask yourself "would a professional game developer give me a better/different/more specific answer to this question than other programmers?"" – concept3d, Josh
If this question can be reworded to fit the rules in the help center, please edit the question.


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();


then to iterate:

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

  • \$\begingroup\$ I take it there is no automatic way to add all enemys to enemyList? \$\endgroup\$ – James Gould Jan 5 '14 at 4:48
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – DrHeinous Jan 5 '14 at 5:04
  • 3
    \$\begingroup\$ @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. \$\endgroup\$ – Andrew Russell Jan 5 '14 at 5:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.