Reputation: 3
I am working on an open world zombie game more like a 2d minecraft i could say.
I can't figure out a way to remove an object from a list without getting an exception thrown. root.getChildren.remove()
works fine, but even though the object can no longer be seen its still there because the zombies get removed they can still manage to follow player and attack. The only way to get the zombies completely removed is by removing them from the list but it throws an exception.
Better explanation:
root.getChildren.remove();
removes the object from being seen color/images. Works fine but the object/zombie is still able to move and attack even though its not visible on the screen.
grassList.remove(grass);
removes the ability of the zombie from moving and attacking. But it throws the annoying exception.
The code works fine during the game. I just need to see how to avoid the exception from being thrown. Please help.
// register each zombie
zombieList.forEach(zombie -> {
// do not allow zombie intersect bullet
for(CircleColorSprite bullet: bulletList){
if(zombie.getBoundsInParent().intersects(bullet.getBoundsInParent())) {
root.getChildren().remove(zombie);
zombieList.remove(zombie);
root.getChildren().remove(bullet);
bulletList.remove(bullet);
}
}
if(swingMarkerEffect) { // if player hits keyboard
if(zombie.getBoundsInParent().intersects(swingMarker.getBoundsInParent())) {
zombie.zombieParticle(particleList, zombie, player, floorWIDTH, floorHEIGHT, root);
}
}
// player health
playerHealth_touchByZombie(player, zombie);
// zombie timer, healthBar
zombie.zombieStartTimer(zombieList, zombie, mobAttractor, swingMarker, swingMarkerEffect, player, root, floorWIDTH, floorHEIGHT);
});
Upvotes: 0
Views: 113
Reputation: 1760
You need to iterate over the list using an Iterator.
for (Iterator<Zombie> iter = zombieList.iterator(); iter.hasNext(); zombie = iter.next()) {
//do your logic
iter.remove() //to remove from the original list
}
Edit: instead of doing a lot of loop iteration, you should think about reorganizing your logic to be event driven.
Upvotes: 3
Reputation: 335
In the documentation of ConcurrentModificationException says this Exception is thrown when you try to modify object of a list from a fail-fast iterator.
So to avoid this I suggest to use the simple for
from java.
Upvotes: 0