Object Reference Not Set To An Instance Of An Object

I’m writing a little test inventory and for some reason this pops up whenever I collide with the item I want to pick up.

Unity says that the problem is in line 57. Everything else works fine.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Inventory : MonoBehaviour
{

    public GameObject inventory;
    public GameObject slotHolder;
    private bool inventoryEnabled;
  

    private int slots;
    private Transform[] slot;

    private GameObject itemPickedUp;


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

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

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

    public void OnTriggerEnter(Collider other)
    {
        if(other.tag == "Item")
            {
            itemPickedUp = other.gameObject;
            AddItem(itemPickedUp);
            }
       
    }

    public void AddItem(GameObject item)
    {
        for(int i = 0; i < slots; i++)
        {
            if(slot[i].GetComponent<Slot>().empty)
            {
                // PROBLEM WITH THE LINE UNDERNEATH
                slot[i].GetComponent<Slot>().item = itemPickedUp;
                slot[i].GetComponent<Slot>().itemIcon = itemPickedUp.GetComponent<Item>().icon;
            }
        }
    }

    public void DetectInventorySlots()
    {
        for (int i = 0; i < slots; i++)
        {
            slot[i] = slotHolder.transform.GetChild(i);
           
        }
    }

}

, I marked it

Line 57 and 58 definitely fall under my definition of “hairy lines of code.”

How to break down hairy lines of code:

http://plbm.com/?p=248

The reason I suggest the above is the following:

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.