12 Replies
this is what happens when it occurs
and this is the code causing it
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
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
like store them in another list?
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
wait this worked as well
okay I guess I know for the future
Thanks!!!
ToList creates a copy
u could also use a
for
loop and enumerate backwards and remove without creating another collection of any kind
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)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