Transform child out of bounds

when i run this code i get the message “Transform child out of bounds”. how do i fix that?

public class Inventory : MonoBehaviour
{
    private bool inventoryEnabled;
    public GameObject inventory;

    private int allSlots;
    private int enabledSlots;
    private GameObject[] slots;

    public GameObject inventorySlots;

    private void Start()
    {
        allSlots = 35;
        slots = new GameObject[allSlots];

        for(int i =0; i < allSlots; i++)
       {
           slots[i] = inventorySlots.transform.GetChild(i).gameObject;
       }
    }


    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.I))
        {
            inventoryEnabled = !inventoryEnabled;
        }

        if (inventoryEnabled == true)
        {
            inventory.SetActive(true);
        }
        else
        {
            inventory.SetActive(false);
        }
    }
}

The value of your “allSlots” variable is bigger than the number of children on your “inventorySlots” object. Instead of using a separate variable, why not just use the number of children in inventorySlots directly?

       for(int i =0; i < inventorySlots.transform.childCount; i++)
       {
           slots[i] = inventorySlots.transform.GetChild(i).gameObject;
       }
1 Like