Cannot apply indexing with [] to an expression of type int

Im following a video tutorial on how to make a simple inventory system but I cant get it to work for some reason, the message that pops up is “Cannot apply indexing with [ ] to an expression of type int” can someone help?

Here’s the code:

using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;

public class Inventory : MonoBehaviour
{

    public GameObject inventory;
    public GameObject slotHolder;

    private int slots;
    private Transform[] slot;

    public void Start()
    {
        // slots being detected
    
        slots = slotHolder.transform.childCount;
        slot = new Transform[slots];
        DetectInventorySlots();

    }

    public void Update()
    {


    }

    public void OnTriggerEnter(Collider other)
    {


    }

    public void AddItem(GameObject item)
    {

    }
    public void DetectInventorySlots()
    {
       // This is where the problem is I think
        for (int i = 0; i < slots; i++)
        {
            slots = slotHolder.transform.GetChild(i);
            print(slot.name);
        }
    }
}

First off, please use code tags: https://discussions.unity.com/t/481379

Second, error messages have line numbers in them. That's how you find the error. At the minimum, be so courteous when you post the above code and actually indicate which line that the error corresponds to in your posted code.

Spoiler: the line numbers are often different between what prints here in the forum, and what prints in your IDE, so a nice and easy...

// error happens in this next line!

... helps us all get on the same page.

Sorry, its my first time… I updated it though, and indicated where I think the problem is. Thank you for your help!

slots = slotHolder.transform.GetChild(i);

"slots" is an int.
Transform.GetChild returns a Transform.
You cannot assign "slots" to a Transform reference.

I'm guessing you may have made a mistake somewhere when following the tutorial.
The name "slots" being given to an int, and "slot" being given to an array makes me believe you may have accidentally swapped the names of these two variables, since arrays are commonly plural-named.

1 Like