Rows:
List<Vector2> tmp_bullets = bullet_i_position; List<Vector2> tmp_enemy = enemy_positions;
they donβt clone the list, they just create a local link to the same list. A direct solution would be to change these two lines to:
List<Vector2> tmp_bullets = new List<Vector2>(bullet_i_position); List<Vector2> tmp_enemy = new List<Vector2>(enemy_positions);
But this will assign a new list every time the method is called, which will be terrible for garbage collection (especially in the game), so the best solution is to remove your foreach loops and replace them with the opposite for the loop. This works because you only get this exception when repeating a collection using counters. The same problem does not apply to regular cycles. For instance:
for (int i = bullet_i_position.Count - 1; i >= 0; i--) { Vector2 bullet = bullet_i_position[i];
Also, the reason for reverse iteration is that deleting an element at regular iteration means that you skip the element after the deleted element (because the indices will shift by 1)
source share