# 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

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].