- Home /
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[i].GetComponent<Slots>().empty)
{
slot[i].GetComponent<Slots>().item = itemPickedUp;
slot[i].GetComponent<Slots>().itemIcon = itemPickedUp.GetComponent<Item>().icon;
}
}
}
public void DetectInventorySlots()
{
for (int i = 0; i < slots; i++)
{
slot[i] = slotHolder.transform.GetChild(i);
}
}
Answer by JDelekto · Apr 27, 2019 at 07:33 PM
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[i] != null)
{
Slots slots = slot[i].GetComponent<Slots>();
if ((slots != null) && (slots.empty))
{
slots.item = itemPickedUp;
Item item = itemPickedUp.GetComponent<Item>();
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220612200322im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Issues with Inventory script 0 Answers
Distribute terrain in zones 3 Answers
Count object list duplicates 1 Answer