- Home /
Array out of its own range?
var farCell = cell.Length;
var middle : Vector3;
middle = cell[farCell].transform.position;
I'm trying to get the transform position of the last element of the array. It's giving me an out of range error. If I negate cell.length by one, I no longer get an error. Suggesting the length of the array is one greater than the length of the array...
Any ideas?
Thanks guys
are you accounting for the array counts 0,1,2,3,4 and so on?
Answer by Kleptomaniac · Apr 22, 2012 at 03:38 AM
Yes, this is because of the structure of arrays. Let me explain.
Say you were to have an array of ints called intArray which contains [5, 10, 15, 20, 25, 30, 35]. The way in which array elements are structured is such that the first element's index is not 1, but 0! From there, indexes continue in consecutive order like so: 0, 1, 2, 3, 4 .. etc.
Therefore, in the case of our example, intArray[0] = 5, intArray[1] = 10, intArray[2] = 15 ... all the way up to intArray[6] = 35. However, the .Length property of an array works as you would expect, in that it returns the number of elements in the array, not any of the indexes. Therefore, since there are 7 elements in intArray, intArray.Length returns 7.
Here's where it gets really trippy however; if you are trying to return the last element of the array (like you are trying to do), you would of course use intArray.Length like you have done. However, if you try to use intArray[intArray.Length], this will return an out of range error.
In simplest terms that is because intArray.Length = 7, and there is no intArray[7] in intArray! The largest element is of index 6 because of the inclusion of an element 0 in the array. Therefore, intArray.Length - 1 is required in order to return intArray[6]. :)
Hope that made sense! Klep
Haha, $$anonymous$$e didn't turn out to be very simple! :D
Answer by AchillesWF · Apr 22, 2012 at 03:37 AM
The Length is the number of items in your array, which are indexed from 0 to the number of items minus 1. So, using farCell is out of range.
Answer by Blackjackjulian · Apr 22, 2012 at 03:36 AM
Cell.length returns the number of elements in the array.
But the elements are numbered from 0 onward.
You're getting element 9 in a 9 element array. But they're numbered 1-8.
Element.length-1.
Answer by aldonaletto · Apr 22, 2012 at 03:33 AM
Like @bodeci said, arrays start at 0, thus the last element is cell.length-1 - cell.length is out of range.
Your answer
Follow this Question
Related Questions
Array index is out of Range!? 1 Answer
Wierd Animation Bug 0 Answers
Why is this array out of length? 1 Answer
Array out of Range 1 Answer
Random object, Array index out of range 0 Answers