Cannot find a class or type named “Enemy” -- How to Initialize an Array of Objects

  int spawnTime=180;
Enemy[] zombieArray;
int zombiecount;
int maxzombie=8;
int i;
 void setup()
{
  maxzombie=8;
 size(500,300); 

 zombieArray = new Enemy[maxzombie];
}
void draw(){
  background (100);
for ( Enemy zomb:zombieArray) {
    if(mousePressed=true){
    zombieArray[i].display();
    zombieArray[i].update();}
}
 
 
 
 
 
 class Enemy
{
  float x,y,speed;
  
    Enemy()
      {x=450;y=random(575,585);speed=1;}
 
  void update(){
    x-=speed;
  }
  
  void display(){
    fill (100,250,100);
      rect(x,y,5,10);}
}
}

1 Like

Hello @C2014 :slightly_smiling_face:

I have made comments next to the lines that need to be changed.

int spawnTime=180;
Enemy[] zombieArray; 
int zombiecount;
int maxzombie=8;
int i; // do not need this, it's declared and initialized in your for-loop(s)

void setup(){
  maxzombie=8;//delete this duplicate, you've already initialized this variable above,
  size(500, 300); 

  zombieArray = new Enemy[maxzombie]; //here you are declaring the number of Enemy object
  
  //Add code here. You need to add a for-loop to initialize the array
  
}
void draw() {
  background (100);
  
  for ( Enemy zomb : zombieArray) {.
    if (mousePressed = true) { // this means you are assigning a VALUE of true. Actually you want to indicate a STATE.
    // change from = to ==.
      zombieArray[i].display();
      zombieArray[i].update();
    }
  }

  class Enemy
  {
    float x, y, speed;

    Enemy() {
      x = 450;
      y = random(575, 585); // these values fall outside the height of your sketch,
      //in setup() you say 300 for sketch height
      speed = 1;
    }

    void update() {
      x-=speed;
    }

    void display() {
      fill (100, 250, 100);
      rect(x, y, 5, 10);
    }
  }
}

I have linked an excellent Coding Train youtube tutorial for initializing an array of Objects:

:nerd_face:

1 Like

You’ve defined your Enemy class inside your draw() function. This is probably not what you want to do. Check your pairs of {}!

3 Likes

Thank you, it helped me!!