C
C#7mo ago
Ab

What does this error mean?

No description
12 Replies
Ab
AbOP7mo ago
Ab
AbOP7mo ago
this is what happens when it occurs
Ab
AbOP7mo ago
and this is the code causing it
No description
Ab
AbOP7mo 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
leowest7mo 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
AbOP7mo ago
like store them in another list?
leowest
leowest7mo 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
AbOP7mo ago
No description
Ab
AbOP7mo ago
wait this worked as well okay I guess I know for the future Thanks!!!
leowest
leowest7mo ago
ToList creates a copy
cap5lut
cap5lut7mo 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
leowest7mo 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