Error When Adding Sprites to a List Outside of the LoadContent() Method

When i try to add sprites to a sprite list from anywhere other than the LoadContent() method, it crashes. The error message is:‘Collection was modified; enumeration operation may not execute.’ I think I understand what this means, but I have no idea why it is showing up. I’m using the sprite class from Oyyou’s tutorials, if you were wondering.

Do you know why this is? If you need more code, just ask. Any help would be appreciated! :smiley:

Hmm. Could do with posting the affected code! :slight_smile:

But it sounds to me like you’re doing a foreach, and then trying to add a new component while in that list.

For that is the case - there are a few options:

  1. Don’t add something to your list while looping through it
  2. Change your loop to a for loop
  3. Do a copy of the list you want to loop around. An example would be:
foreach (var sprite in _sprites.ToArray())
  ; // code here

Notice the “ToArray()”. That means you’re not longer references the same list, so you can modify it all you like.

Thanks! Works perfectly now! :smiley: