Hi, I’m trying to draw multiple instances of the class Enemy.cs
I’m able to add 3 enemies to the Enemies list but I can’t draw them.?
Code:
Game1.cs
public class Game1: Game {
List<Enemy> Enemies = new List<Enemy>();
Enemy en = new Enemy();
Vector2 enemyPosition = (0, 200);
protected override void Initialize(){
base.initialize();
en.Initialize(Content.Load<Texture2D>("Enemies/greenballoon"), new Rectangle(0,0,60,170)); //I have to initialize it with something at first or else it'll crash with a null exception.
}
protected override void Update(GameTime gameTime){
foreach (Enemy enemy in Enemies){
en.update(gameTime);
}
battle();
}
public void battle()
{
if (Enemies.Count < 3)
{
Enemy enemy = new Enemy();
enemy.Initialize(texture, new Rectangle((int)enemyPosition.X,(int)enemyPosition.Y,60,170));
Enemies.Add(enemy);
enemyPosition.X += 20;
}
}
protected override Draw(GameTime gameTime){
foreach (Enemy enemy in Enemies)
{
en.update(gameTime);
}
battle();
}
}
Enemy.cs
class Enemy
{
public Texture2D Texture;
public Rectangle Box;
public void Initialize(Texture2D enemyTexture, Rectangle enemyBox)
{
Texture = enemyTexture;
Box = enemyBox;
}
public void update(GameTime gameTime)
{
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Texture, Box, Color.White);
}
}
I checked to see if there are 3 enemies in Enemies and there are. They exist, I just can’t see them. I can only see one.(Probably the one initialized in Initialize? and not battle())
So yeah. Here’s the screenshot of the problem in the game
It says
foreach (Enemies enemy in Enemies){
en.draw(spriteBatch);
}
Does it not?? I don’t understand why it’s only drawing one when there’s clearly 3.
Thanks for reading and I’m hoping to hear from you. Also if you have any advice on how I can keep better organized or more professional ways to set up this kind of code please let me know, thanks.