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);
	}
}

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) ?

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
   }
}

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.