Object Reference Not Set To An Instance of An Object Error

Keep getting this error. NullReferenceException: Object reference not set to an instance of an object
Inventory.AddItem (UnityEngine.GameObject item) (at Assets/Scripts/Character/Inventory.cs:53)
Inventory.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/Character/Inventory.cs:45)

Here is my code:

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.Tab))
    {
        inventoryEnabled = !inventoryEnabled;
    }

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

}

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

public void AddItem(GameObject item)
{
    for(int i = 0; i < slots; i++)
    {
        if(slot*.GetComponent<Slots>().empty)*

{
slot*.GetComponent().item = itemPickedUp;*
slot*.GetComponent().itemIcon = itemPickedUp.GetComponent().icon;*
}
}
}
public void DetectInventorySlots()
{
for (int i = 0; i < slots; i++)
{
slot = slotHolder.transform.GetChild(i);
}
}

According to the call stack, your exception is occurring inside the call to AddItem() (which was in turn called by your trigger.

Is it possible that there is an item in your slot array which does not have a “Slots” component on it? If so, your if() statement will throw that exception when trying to access the “empty” property. Also, may I suggest perhaps optimizing this a bit? For example:

public void AddItem(GameObject item)
{
	if (itemPickedUp == null)
		return;

	for (int i = 0; i < slots; i++)
	{
		if (slot *!= null)*
  •  {*
    

_ Slots slots = slot*.GetComponent();*_

* if ((slots != null) && (slots.empty))*
* {*
* slots.item = itemPickedUp;*

* Item item = itemPickedUp.GetComponent();*

* slots.itemIcon = (item != null) ? item.icon : null;*
* }*
* }*
* }*
}
It looks more verbose, but it’s not calling GetComponent<> more than it has to in order to get the associated component. In addition, it’s doing extra checks to make sure those components are not null before they get accessed.
It’s quite possible you either had a game object which was missing a Slots component or you had an Item component which was missing an icon.