- Home /
(C#) ArgumentOutOfRangeException: Parameter name: Index
So this problem has been driving me crazy. I have some problem with trying to use a simple list, so I distilled it down to the most basic script and it's STILL giving me problems. I've looked at other examples but the problem is either something else or the code is too complicated to actually see what's going on.
Basically I'm making a list, putting numbers in it (from 0 to 5), and printing those numbers to the console.
The result of running the below script is:
Console: 5 (printing "iterations")
Console: 0(printing the first value of "i")
ArgumentOutOfRangeException: Argument is out of range. Parameter name: index
Script:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class arrayTests : MonoBehaviour {
//List<int> testNumberList;//make the list<int>
//List<int> testNumberList = new List<int>();//make the list<int>
//same problem if done outside or inside "start", or declared outside and initialized inside.
// Use this for initialization
void Start () {
List<int> testNumberList = new List<int>();
int iterations = 5; //go through 5 iterations
print(iterations.ToString()); //print this to console
for (int i =0; i<iterations; i++)//for however many iterations (5)
{
print(i.ToString());//what "i" are we on?
testNumberList[i] = i;//put "i" in the list
print(testNumberList[i]);//prove that "i" is in the list now
}
}
// Update is called once per frame
void Update () {
}
}
I tested explicitly declaring the capacity of the list, even though the whole point of using them is you dont have to, and it still wont work.
tried: List testNumberList = new List(10); yet it still says that trying to put infomration in index at 0 is "out of range"?
Answer by Graham-Dunnett · Oct 14, 2011 at 09:42 PM
Can you set a value in the List using Array notation? I'd use:
testNumberList.Add( i);//put "i" in the list
When you try to access the i'th element to set it using array notation, surely it does not exist (yet)? If you want to set at a given index position use:
testNumberList.Insert(i,i);
You sir are a gentleman and a scholar. I changed the for loop to:
for (int i =0; i
and it works perfectly!
I was under the (mistaken) impression that i was simply adding the value to the list, but you're right, now I see what I was actually trying to do was ASSIGN "i" INTO the current [0] slot, when the list in fact had no slots. Thank you, you won't believe how much this little problem has been driving me crazy!
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Need help with converting an array to a list in C#` 4 Answers
sort list by variable in list of ints array 2 Answers
Need some help looping through an array or list 2 Answers
Dynamic update List<> 1 Answer