for (int i = 0; i < 3; i++) {
Debug.Log(“works”);
GameObject piece = LM.offBoard [0];
LM.offBoard.Remove (piece);
}
In this code, on the second iteration of the loop, Unity throws an ArgumentOutOfRangeException. Why does it do this, and how can I fix it?
This exception is thrown since when you remove an element from the list, the size of list changes resulting in ArgumentOutOfRangeException. Say you have three elements in the list and you removed one then the size of list became two but your for loop will still try to access the third element even when it is not present.
One counter method could be to loop through your list in reverse order.
for (int i = LM.offBoard.Count - 1; i >= 0; i--) {
Debug.Log("works");
GameObject piece = LM.offBoard [0];
LM.offBoard.Remove (piece);
}