How to loop through objects?

Yes. Instead of having one object for each of your crops, put all your crops in an array. It’s like a list of them.

Becomes just:

Crop[] crops = new Crop[12];

Now you suddenly have space for a dozen Crop objects! Next, use a loop to create them. Since this only happens once, do it in setup():

for( int i = 0; i < crops.length; i++){
  crops[i] = new Crop(0);
}

Now you can loop over them in draw() too, to draw them.

BONUS THOUGHT: Can you write a function in the Crop class that detects if a mouse was clicked on that crop? The Crop class will need to know a few things about itself… like its position…

See also: Arrays / Processing.org

2 Likes