出於某種原因,我看了很多帖子,但我不知道如何解決這個問題。 在我的遊戲的更新方法中,我有一個更新所有現有GameObjects的for循環。怪異的併發修改異常
private static void update() {
for (GameObject g : GameObjectManager.getGameObjects()) {
g.update();
}
canvas.repaint();
}
它說在for循環行有一個ConcurrentModificationException錯誤。 我曾嘗試過,像有人說的那樣,獲取遊戲對象列表的迭代器,然後使用它,但它仍然不起作用。 儘管它表示錯誤行位於for循環,但當我刪除g.update時,沒有更多錯誤。 編輯:我發現了錯誤。它將一個遊戲對象添加到GameObjectManager.registerGameObject()中的列表中。 使用了更新的唯一其他類是這樣的:
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);
}
}
}
唯一的更新方法是這樣的:
@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));
}
}
問題不是GameObjects被修改,而是列表本身,而迭代它: GameObjectManager.getGameObjects()<----這個調用返回的列表。也許g.update()從這個列表中刪除或添加其他GameObjects? – Chrisport 2014-11-02 19:59:03