- Home /
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
Answer by akirassasin_dev · Jul 19, 2016 at 11:27 AM
I found out what was the cause. It was a silly mistake on my part :)
I created 2X of nodes while still adding only X amount of things into the List.
Answer by CardboardComputers · Jul 10, 2016 at 08:23 AM
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.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Insert a string to a list inside a list 3 Answers
JS Argument out of range 1 Answer
Argument out of range exception 1 Answer
How do I return the index of an array of sprites as an int? 1 Answer