- Home /
for loop problem
hello everyone, i`ve been away from unity for a while and im getting a bit of truble with a for loop, it`s supposed to fill an array with the distances at which to spawn objects, here is how it looks like:
void Update () {
for (int i = 0; i < 10; i ++){
distPerSs[i] = -0.25f * i + 500; //error here
print("Pos: " + distPerSs[i]);
}
its based in a linear function in which, if i = 0 the value of distPerSs would be 250, and if i = 1000 the distPerSs = 500, yet its giving me an error of "index out of range" in the marked line. any ideas and suggestions are much apreciated
"index out of range" means that you are trying to access a part of the array that does not exist. If your array is 10 in length, then you can access 0 -> 9 . Check your value for i and make sure that it starts at 0 and that the loop ends when i is the length of the array -1. Use a Debug.Log statement to see what is going on :)
Answer by devluz · Nov 04, 2014 at 11:52 PM
Not sure what your want to do in detail but the error means you try to write or read data from an index that doesn't exist.
e.g. if your array distPerSs has the length of 10 so you create it with this: float[] distPerSs = new float[10]; then you can only use it with index 0 to 9 (distPerSs[0] to distPerSs[9]) but not distPerSs[10].
So the important part is how big is your list? e.g. for the length 10 you could easily do this:
float[] distPerSs = new float[10];//here you decide the length
for (int i = 0; i < distPerSs.Length; i ++) //using distPerSs.Length instead of 10
{
distPerSs[i] = -0.25f * i + 500; //error here
print("Pos: " + distPerSs[i]);
}
If you do it like this you can change the length easily how you need it without breaking your loop
Your answer

Follow this Question
Related Questions
Insert a semicolon error 1 Answer
x=x Assignment made to same variable 3 Answers
2 Scripting Errors I need help fixing!! 3 Answers
Array index is out of range? 1 Answer
Help solving for loop error 1 Answer