- Home /
JS: Array index not taking array.length as valid int?
Hey guys, have a little code here that should put pickedup gameobjects in an Array. The following code generates this error:
"ArgumentOutOfRangeException: Index is less than 0 or more than or equal to the list count"
code:
var objectarray: Array = new Array();
var arraycount:int = 0;
function Update () {
}
function AddObject(o:GameObject){
print("ObjectInventory: Object Added");
objectarray.Add(o);
arraycount = objectarray.length;
print(objectarray);
objectarray[arraycount].transform.position = Vector3(11, 0.7, -21.45);
}
If I set a hard index int (like 0), the code works, but not when I derive it from objectarray.length.
I tried arraycount = int(objectarray.length); But that doesn's seem to wrk either.
Anyone any tips? Much appreciated!
Answer by BarkShark · Jan 08, 2012 at 11:15 AM
At the last line of your code when you write this : objectarray[arraycount]
, you try to acces an element in the array at a certain index. In this case the amount of elements in the array. You have to know that an array index doesn't start at 1 but at 0. So objectarray[0]
is actually the first object. And objectarray[1]
the second.
So the length of an array is always 1 bigger than the index of the last object. If you try to acces an index that is bigger than the array length it will trow in that error. If you want to acces the last object in your array like you tried in your script use this : objectarray[arraycount-1]