Transform child out of bounds

I’m getting this error: UnityException: Transform child out of bounds

I google it and it means I’m trying to access a child which doesn’t exist, eventhough my child does exist.

I’m trying to access to a text which is the 2nd children of an image:

The line with the error is this one inside the “else if” statement:

Text text = child.GetChild(1).GetComponent();

Here’s the code:

void RefreshInventory()
    {
        int i = 0;
        foreach (Transform child in transform)
        {
            slotsList _= inventoryList*;*_

if (slotsList*.itemName != null)*
{
Image image = child.GetChild(0).GetComponent();
image.enabled = true;
image.sprite = slotsList*.itemIcon;*
if (slotsList_.itemStackable == true && slotsList*.itemStack > 1*
{
Text text = child.GetChild(1).GetComponent();
text.enabled = true;
text.text = slotsList*.itemStack.ToString();*
}
}
else if (slotsList*.itemName == null)*
{
Image image = child.GetChild(0).GetComponent();
image.enabled = false;
image.sprite = null;
Text text = child.GetChild(1).GetComponent();
text.enabled = false;
}
i++;
}
}
Thanks :slight_smile:_

This script works only if it’s attached to the game object “Inventory”, anyway I would use FindChild(“Image”) and FindChild(“Text”) instead of GetChild because so it’ll work even if the first child is “Text” instead of “Image”.