I have been looking for the reason why I get this error message for several days now! And I need help to solve this or to improve the code. It’s hard to understand why this error happens and find the reason, when it just happens sometimes and not all the time! But my guess is that it has to do with the list and the numbers of items in the lists. It’s in the second part of the code where the error event happens. I have also tried to add the objects that I want to remove in a special “to remove list”, but why should this not work? Help is appreciated! Thanks!
public void CollisionControlMissileHitAsteroid(ContentManager content)
{
for (int i = 0; i < missilesList.Count(); i++)
{
// Stora asteroider
for (int j = 0; j < asteroidsBigList.Count(); j++)
{
if (missilesList.ElementAt(i).Bounds().Intersects(asteroidsBigList.ElementAt(j).Bounds())) // Fel här ??
{
for(int x = 0; x < 2; x++)
AddNewSmallAsteroidToList(new AsteroidSmall(content, asteroidsBigList.ElementAt(j).Position));
missilesList.RemoveAt(i);
i--;
asteroidsBigList.RemoveAt(j);
j--;
}
}
if (missilesList.Count() > 0 && asteroidsSmallList.Count > 0)
{
for (int k = 0; k < asteroidsSmallList.Count(); k++)
{
if (missilesList.ElementAt(i).Bounds().Intersects(asteroidsSmallList.ElementAt(k).Bounds())) // THIS IS WHERE THE ERROR EVENT HAPPENS!
{
missilesList.RemoveAt(i);
i--;
asteroidsSmallList.RemoveAt(k);
k--;
}
}
}
}
}
EDIT:
Is this where I should place the break? Ask beacause it still happens! I can play for five minutes until it happens!
if (missilesList.Count() > 0 && asteroidsSmallList.Count() > 0)
{
for (int k = 0; k < asteroidsSmallList.Count(); k++)
{
if (missilesList.ElementAt(i).Bounds().Intersects(asteroidsSmallList.ElementAt(k).Bounds()))
{
missilesList.RemoveAt(i);
i--;
asteroidsSmallList.RemoveAt(k);
k--;
break; // ???????
}
}
}
Suppose you start off with one missile and two asteroids. The missile (i=0) hits the first asteroid (j=0) – but you’re then continuing with i=-1 and j=0. You should be breaking out of the inner loop and continue with the next iteration of the outer loop there instead. After all, you’re “done” with the missile – it can’t hit any other asteroids, big or small.
(And yes, as per xanatos’s comments, it would be more idiomatic to use the
Countproperty instead of theCount()method.)