c# - Remove object from List<> on condition -


i creating ant simulation program ants travel around , collect food , bring nest. when number of ants have collected food want food source disappear. have separate class antobject, foodobject , nestobject.

i have 'int foodleft = 25' variable in stationaryfood class. foodobjects placed onto screen when user clicks, , added list object 'foodlist'. draw method draws objects in list. cannot figure out how make specific food object disappear when 'foodleft' variable hits 0!

here draw method in stationaryfood class -

  public void draw(spritebatch spritebatch, list<stationaryfood> foodlist)     {         foreach (stationaryfood food in foodlist)         {             spritebatch.draw(foodimage, foodboundingrectangle, foodcolor);                                                              //draw each food object in foodlist         }     } 

and here attempted solution problem in main 'game1' class in update method

  if (foodlist.count > 0)         {             foreach (stationaryfood f in foodlist)             {                 if (f.foodleft == 0)                 {                     foodlist.remove(f);                   }             }         } 

however not work! 'unhandled invalid operation error'.

in draw method in main game1 class have

        foreach (stationaryfood f in foodlist)         {             f.draw(spritebatch, foodlist);         } 

can see going wrong?

you're modifying collection you're iterating through it, hence why you're getting exception. in case, instead of this:

foreach (stationaryfood f in foodlist) {     if (f.foodleft == 0)     {         foodlist.remove(f);     } } 

do instead (assuming it's available in xna):

foodlist.removeall(x => x.foodleft == 0)

if isn't, can @ answer in this question alternative.


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -