Transform Child out of bounds

Hello everyone, hope you are having a nice day!

I have an inventory script that gets all of the slots in the slotholder object, but it pumps out an error:

UnityException: Transform child out of bounds

I can not for the life of me figure out what is causing this error, So I am asking for help, if you need more information, ask me.

for (int i = 0; 1 < slots; i++)
        {

            // Detecting all slots that are child of the slot holder.

            slot[i] = slotHolder.transform.GetChild(i);
        }

What is your “slots” variable?

In your case, the “slots” variable is larger than the actual size of the “slot” array. You are basically trying to access a place in the array that does not exist. Also, where are you reducing the size of the “slots” variable? Your loop will go until 1 < slots, which in the case you’ve shown will be never (since slots value never changes) or always (in which case it won’t even enter the loop).

Instead of using the “slots” variable, try using slot.Length

You can use Transform.childCount to get the number of children that slotHolder has.

for(int i = 0; i < slotHolder.transform.childCount; i++)
{
    slot[i] = slotHolder.transform.GetChild(i);
}

Another option that takes care of bounds for you is just to just a foreach on the transform:

        foreach (Transform child in transform)
        {
            // Do things
        }
1 Like

This is what I was going to do, because it is what i did for other c# projects outside of unity, but I had trouble getting it to work, thank you for your help :slight_smile: