C
C#6mo ago
Ab

What does this error mean?

No description
12 Replies
Ab
AbOP6mo ago
Ab
AbOP6mo ago
this is what happens when it occurs
Ab
AbOP6mo ago
and this is the code causing it
No description
Ab
AbOP6mo ago
for some reason, when the collision occurs and I try to remove the bullet from the list, it gives that error and crashes I rendered the colliders to make it easier to see
leowest
leowest6mo ago
u can't modify the collection while iterating over it u would have to store the items u want to remove and remove after u iterate over it
Ab
AbOP6mo ago
like store them in another list?
leowest
leowest6mo ago
yeah u would have say outside the foreach var itemToRemove = new List<Bullet>(); and u would add to it then after the foreach u perform the removal
Ab
AbOP6mo ago
No description
Ab
AbOP6mo ago
wait this worked as well okay I guess I know for the future Thanks!!!
leowest
leowest6mo ago
ToList creates a copy
cap5lut
cap5lut6mo ago
u could also use a for loop and enumerate backwards and remove without creating another collection of any kind
for (int i = GameManager.bulletList.Length - 1; i >= 0; i--)
{
GameManager.bulletList.RemoveAt(i);
}
for (int i = GameManager.bulletList.Length - 1; i >= 0; i--)
{
GameManager.bulletList.RemoveAt(i);
}
it will be also faster than list.Remove(bullet) because this one would have to search for where bullet actually is, so u get down from a complexity of O(n²) to O(n)
leowest
leowest6mo ago
and u also avoid the tolist copy which can be awful depending how big your list is, specially for a game where every perf counts; my only worry there was whether or not that list could be modified else where which I dont know
Want results from more Discord servers?
Add your server