1

This is my first attempt to implement Entity Component System in my project and I'm not sure how some of its mechanics works. For example do I remove an entity? Since all systems are using entities list throughout whole game loop, every attempt of deleting element of that list is condemned to ConcurrentModificationException. Going by this advice I've tried to setting some kind of "toRemove" flag for entities and look for it every time system iterate through list

public class DrawingSystem extends System {

    public DrawingSystem(List<Entity> entityList) {
        super(entityList);
    }

    public void update(Batch batch) {
        for (Entity entity : entityList) {
            removeIfNeccesarry(entity);
            //code

            }
        }

        public void removeIfNeccesarry(Entity entity){
            if(entity.toRemove){
                entityList.remove(entity);
            }
        }

    }

but that didn't help getting rid of the exception. I'm sure there is a elegant solution to this problem since this design pattern is broadly used but I'm just not aware of it.

JohnnyGat
  • 325
  • 2
  • 13
  • The reason you're still getting a CME is because you're still removing the entity from `entityList` in the middle of iterating through it. Have a look here for a solution: https://gamedev.stackexchange.com/questions/2647/how-do-i-best-remove-an-entity-from-my-game-loop-when-it-is-dead – Steve Smith Apr 24 '18 at 06:23

1 Answers1

0

Check out iterators:
"Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics."
https://docs.oracle.com/javase/8/docs/api/index.html?java/util/Iterator.html

    Iterator<Entity> it = entityList.iterator();
    while (it.hasNext()) {
        Entity entity = it.next();

        if (...) {
            it.remove();
        }
    }

You could also store the indices of the entities to remove somewhere outside the list and then remove the dead entities in an extra step after the update/render.
This has the advantage that you do not miss entities in later steps of your update.

Edit: Added code.

  • Welcome to SO. Although your answer is correct, it is always encouraged to put some code examples in your answers. Codes helps grabbing the attention over a too wordy answers. – Amit Phaltankar Aug 27 '18 at 22:37