I’m trying to implement a particle system in my game, but have run into a snag.
I store all created Emitters in a List . Each update cycle I iterate through all of them and have them emit unless their timeToLive has expired, in which case I need to remove them from the list. But, If I try to remove a dead Emitter in the for loop where I’m iterating through them, I get an exception.
Here is the problematic code.
for(Emitter emitter : emittersList) {
if(emitter.isDead()) {
emittersList.remove(emitter); // Causes Runtime Error
}
else {
emitter.emit(elapsedMS, particlesList);
}
}
My current solution is to add another list which holds all dead Emitters that need to be removed, and then remove them all after iterating through.
Like this.
for(Emitter emitter : emittersList) {
if(emitter.isDead()) {
deadEmittersList.add(emitter);
}
else {
emitter.emit(elapsedMS, particlesList);
}
}
emittersList.removeAll(deadEmittersList);
deadEmittersList.clear();
So, is there a solution for this, that is more efficient and doesn’t require a seperate Dead Emitter list?