How is this array index outside the bounds of the array?

Getting an out of bounds exception on an array with 3 indexes that’s not changed or referenced anywhere else in my project… Its not finding the third child of the object for some reason. Can someone point out whats wrong here I’m so confused

//Slots display
    private GameObject[] slotsDisplay;

    private GameObject slot0;
    private GameObject slot1;
    private GameObject slot2;

    private void Start()
    {
        //slots init
        slotsDisplay = new GameObject[2];

        //Slot 0
            slot0 = gameObject.transform.GetChild(0).gameObject;
            slotsDisplay[0] = slot0;
        //Slot 1
            slot1 = gameObject.transform.GetChild(1).gameObject;
            slotsDisplay[1] = slot1;
        //Slot 2
            slot2 = gameObject.transform.GetChild(2).gameObject;
            slotsDisplay[2] = slot2;
    }

You created the array with only 2 slots…

slotsDisplay = new GameObject[2];

The issue is on the above line. When you initialise an array, you provide a length. This is, how much space it has. An array with a length of two has, of course, room for two entries, indexes 0 and 1.

Provide a length of 3 and the issue goes away. Though it may just be easier to use a List<T>.

I forgot how arrays work ¯_(ツ)_/¯

It’s always good to review.

Here are some notes on IndexOutOfRangeException and ArgumentOutOfRangeException:

http://plbm.com/?p=236

Steps to success:

  • find which collection it is (critical first step!)
  • find out why it has fewer items than you expect
  • fix whatever logic is making the indexing value exceed the collection
  • remember you might have more than one instance of this script in your scene/prefab