remove object in class

i have a class and i want in the class void remove a object...

class object {
  void draw(){
    if(mouseX>0){
      remove();
    }
  }
}

Answers

  • remove it from where?

  • Answer ✓

    here is an example where we remove a ball from an ArrayList

    you need to loop backward through the ArrayList with a for loop

    ArrayList<Ball> balls;
    
    void setup() {
    
      size(400, 800);
      balls = new ArrayList();
    
      // for-loop
      for (int i = 0; i < 10; i++) { 
    
        int rectWidth = 20;
        int rectHeight = 20;
        float rCol, gCol, bCol;
    
        rCol = random(255);
        gCol = random(255);
        bCol = random(255);
    
        color newColor = color(rCol, gCol, bCol);
    
        Ball newBall = new Ball(random(width-rectWidth), random(height-rectHeight), 
          rectWidth, rectHeight, 
          newColor); 
    
        balls.add(newBall);
        //
      } // for
      //
    } // func 
    
    void draw() {
    
      background(255); // white
    
      // for-loop
      for (int i = 0; i < balls.size(); i++) { 
        Ball ball = balls.get(i);
        ball.display( false );
      } // for
    
      for (int i = balls.size()-1; i>=0; i--) { 
        Ball ball = balls.get(i);
        if (!ball.isAlive) // ! means not 
          balls.remove( i );  // remove i from list
      } // for
    
      fill(0);  // black 
      text ("number "+balls.size(), 
        14, 14); 
      //
    } // func 
    
    // ==================================================
    
    class Ball {  
    
      // position
      float x;
      float y;
      // size
      float w;
      float h;
      // color 
      color colBall;  
      // Is it still alive?
      boolean isAlive = true; 
    
      // constr 
      Ball(float tempX, float tempY, 
        float tempW, float tempH, 
        color tempColBall) {
        x = tempX;
        y = tempY;
        w = tempW;
        h = tempH;  
        colBall = tempColBall;
      } // constr 
    
      void display( boolean withStroke ) {
    
        if (withStroke) {
          strokeWeight(3); 
          stroke(0);
        } else {
          noStroke();
        }
        fill(colBall);
        rect(x, y, w, h);
    
        y+=3;
    
        if (y > height+12) 
          isAlive = false;
      } // method 
      //
    } // class
    //
    
Sign In or Register to comment.