I am trying to remove object while I am iterating through Collection. But I am getting exception. How can I achieve this? Here is my code :
foreach (var gem in gems)
{
    gem.Value.Update(gameTime);
    if (gem.Value.BoundingCircle.Intersects(Player.BoundingRectangle))
    {
       gems.Remove(gem.Key); // I can't do this here, then How can I do?
       OnGemCollected(gem.Value, Player);
    }
}
                foreach is designed for iterating over a collection without modifing it.
To remove items from a collection while iterating over it use a for loop from the end to the start of it.
for(int i = gems.Count - 1; i >=0 ; i--)
{
  gems[i].Value.Update(gameTime);
  if (gems[i].Value.BoundingCircle.Intersects(Player.BoundingRectangle))
  {
      Gem gem = gems[i];
      gems.RemoveAt(i); // Assuming it's a List<Gem>
      OnGemCollected(gem.Value, Player);
  }
 }
If it's a dictionary<string, Gem> for example, you could iterate like this:
foreach(string s in gems.Keys.ToList())
{
   if(gems[s].BoundingCircle.Intersects(Player.BoundingRectangle))
   {
     gems.Remove(s);
   }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With