For some reason I have looked at lots of posts and still I don't know how to fix this. In the update method of my game, I have a for loop that updates all the existing GameObjects.
private static void update() {
for (GameObject g : GameObjectManager.getGameObjects()) {
g.update();
}
canvas.repaint();
}
It says there is a ConcurrentModificationException error at the line of the for loop. I have tried, like some people said, to get the iterator of the game object list and then use that, but it still doesn't work. Even though it says the error line is at the for loop, when I remove g.update there is no more error. EDIT: I found the error. It adds a game object to the list in the GameObjectManager.registerGameObject(). The only other class that uses the update is this:
public class PaintCanvas extends JPanel {
private static final long serialVersionUID = 6718161148154673832L;
{
this.setDoubleBuffered(true);
this.setVisible(true);
}
@Override
public void paint(Graphics g) {
g.setColor(Color.RED);
for (GameObject go : GameObjectManager.getGameObjects()) {
g.fillRect(go.getPosition().getX(), go.getPosition().getY(), 30, 30);
}
}
}
The only update method is this:
@Override
public void update() {
Random r = new Random();
int spawn = r.nextInt(100);
// 5% Chance to spawn
if (spawn <= 5) {
Spawner s = new Spawner();
s.setPosition(new Point(4, 50));
}
}