- Home /
Array error - Index is less than 0...
Hi,
I have an array. Whenever I add something to that array, it keeps giving me the following error:
ArgumentOutOfRangeException: Index is less than 0 or more than or equal to the list count.
What causes this and how can I fix this? I searched through similar answers but I still can't get mine to work. Most other users have a for loop and I don't use one.
The thing is that I need to do something when [0] and [1] are filled. So I check if [0] is empty and then execute a code.
var playerInventory = new Array ();
function Update() {
if(playerInventory.length > 0){
if(playerInventory[0] != null){
// do something
}
if(playerInventory[1] != null){
// do something
}
}
for (var value : String in playerInventory) {
print(value);
}
}
Answer by derrtyones · Aug 29, 2012 at 02:12 PM
It works fine now when I check it with:
if(playerInventory.length == 1)
and do that for each element. It does not matter for this array as it will get a max amount of items.
Answer by lvictorino · Aug 29, 2012 at 11:39 AM
When you test `playerInventory.length`, the fact that it returns more than 0 does not mean that it actually contains 2 entry. So when you want to know what is filled in `playerInventory[1]` (the second index actually) you can't be sure it actually exists.
Does it work better with : `if(playerInventory.length >= 2)` ?
It works slightly better, but it's not solved yet. When I hit the first box to add something into that array, no errors are shown. When I hit the 2nd box (2nd data is added to the array) the same error pops up. But then when I hit the third box to add a third piece of data to the array, the error is gone. How do I fix this?
Can you please paste us how you "add" something to your array ?
gameObject.Find("itemHolder").GetComponent("playerInventory").playerInventory.Push(gameObject.tag);
And when you display playerInventory.Length what do you have ?
When I start the game it says 0. When I pick up all 3 items (by touching the boxes) it says 3.
Answer by speedything · Aug 29, 2012 at 12:18 PM
Would a list work better? As arrays are of a fixed size, they are always the same length - regardless of what they contain.
If you do want to keep using an array then I don't think you want to be checking the length, and you'd be better off just checking the individual items. So...
function Update()
{
if ((playerInventory[0] != null) && (playerInventory[1] != null))
{
// Do what you want to do here
}
}
The suggestion to not check for the length, but to only check for individual items ins$$anonymous$$d is nice, but when I do that, I still get the error: Index is less than 0 or more than or equal to the list count.