ArgumentOutOfRangeException: Argument is out of range in Generic.List

I know this error has been asked many times but none of them seem to answer my problem.

TLDR: No problems at getting values from index but still getting ArgumentOutOfRangeException.

I have an object with the script Spawner.
Spawner’s Start will:

add 0 into a static List x times

add 1 into the same List x times

Instantiate an object (Pivot) and call a function Initialize from Pivot. This happens y times.

Pivot's Initialize will Instantiate a child (Node).

Node’s Start will:

get a random index from Spawner's List.

get the value at that index

Debug.Log( value at index)

and removeAt the index.

In total I have 20 Nodes Instantiated. This error appears AFTER ALL the Debug.Logs are called. The error seems to come from
value = listName[random index], yet I still got the values I needed (10 Nodes with 0 and 10 Nodes with 1)

ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index

The method List.RemoveAt(index) modifies the list, such that if there are 10 elements and you remove the first element, then the last index will be 8. If a Node has stored the index 9 (originally the last index) and calls RemoveAt(9) after another Node has called RemoveAt([0–9]), the index will be out of bounds.

Furthermore, if x < y, at least one index will be removed twice.

I found out what was the cause. It was a silly mistake on my part :slight_smile:

I created 2X of nodes while still adding only X amount of things into the List.