Hi. I've looked around but not found a decent solution to this.
- Suppose I have a class which defines a Sprite (x, y, etc.)
- Then I create a List<Sprite> called sprites
- Then in my game loop I go: foreach(Sprite s in sprites) s.render();
- But in the render function of my Sprite class, I want a bit to go: if (offscreen) sprites.Remove(this);
But when the instance tries to delete itself from the queue, I get “Collection was modified; enumeration operation may not execute”.
I can understand why this error is happening. Is there an elegant way of, within the class itself, the instance saying “I want to destroy myself”?
The main solution would be to have a simple “active” boolean as part of the class, and set to True upon instantiation and then False upon self-destruction, but the idea of the List building up with inactive instances sounds a bit rubbish.