Jump to content
  • Advertisement
Sign in to follow this  
Andy474

XNA InvalidOpperationException in foreach loop

This topic is 3419 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

ok, the purpose of this code is to remove all Bullets and Soldiers on the map once certain event are triggered
THIS IS THE ENTIRE VOID"
private void Cleanup()
        {
            if (Bulletlist.Count > 0)
            {
                foreach (Bullet bullet in Bulletlist) // 'in' causes Error
                    Bulletlist.Remove(bullet);
            }
            if (NPCList.Count > 0)
            {
                foreach (NPC soldier in NPCList)
                    NPCList.Remove(soldier);
            }
        }
when i run this code and execute this method I get an InvalidOperationException at the Keyword 'in' and i cant figure out why this is tripping Any ideas?

Share this post


Link to post
Share on other sites
Advertisement
You cannot modify a list you are enumerating. Furthermore, just set the list to null, or create a new list in its place and let the GC deal with cleaning up your discarded list of bullets and soldiers, or call List.Clear().

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!