NullReferenceException: Object reference not set to an instance of an object

So I keep getting this error with my code for an inventory system. I see nothing wrong in the code, so there must be a different way to write it. Could someone tell me what is missing in this?

Inventory Script

public class Inventory : MonoBehaviour
{
    public GameObject player;
    public GameObject Bar;

    public static Inventory instance;

    public List<Item> list = new List<Item>();

    public void UpdatePanelSlots()
    {
        int index = 0;
        foreach (Transform child in Bar.transform)

        {
            InventorySlotController slot = child.GetComponent<InventorySlotController>();

            if (index < list.Count)
            {
                slot.item = list[index];
            }
            else
            {
                slot.item = null;
            }
            slot.Updateinfo();
            index++;
        }
    }
    void Start()
    {
        instance = this;
        UpdatePanelSlots();
    }
    public void Add(Item item)
    {
        if (list.Count < 3)
        {
            list.Add(item);
        }
        UpdatePanelSlots();
    }
    public void Remove(Item item)
    {
        list.Remove(item);
        UpdatePanelSlots();
    }
}

InventorySlotController Script

public class InventorySlotController : MonoBehaviour
{
    public Item item;

    private void Start()
    {
        Updateinfo();
    }

    public void Use()
    {
        if (item)
        {
            item.Use();
        }
    }
    public void Updateinfo()
    {
        Image displayImage = transform.Find("Image").GetComponent<Image>();

        if (item)
        {
            displayImage.sprite = item.icon;
        }
        else
        {
            displayImage.sprite = null;
        }
    }
}

Item Script

public class Item : ScriptableObject
{
    public string itemName;
    public Sprite icon;

    public virtual void Use()
    {

    }
}

Please copy and paste the error from the console. It contains information about what line is throwing the error.

NullReferenceException: Object reference not set to an instance of an object
Inventory.UpdatePanelSlots () (at Assets/Scripts/Inventory.cs:28)
Inventory.Start () (at Assets/Scripts/Inventory.cs:37)

This error often comes not from code, but from data. Look at the line what throws the error and check object required exists and fields in inspector are set to valid references. Basically this error means you’re trying to access something what do not exists.

check the inspector and make sure the public variables are referencing an object

double click the error on console and it should highlight the line throwing the error in visual studio

I’m guessing that your “Bar” game object has some child objects that don’t have an InventorySlotController, maybe some graphics-only objects?

1 Like