GetComponent apparently not set to instance of an object

Hi so I make a Inventory and I have an class named Item and a MonoBehaviour class named ItemProperties.
Testwise these only contain a name and icon. When I try to add it to my Inventory it says that it is not set to the instance of an object.

void OnCollisionEnter2D(Collision2D other)
    {
        if(other.gameObject.tag == "Item")
        {
            for(int i = 0; i < 9; i++)
            {
                if(items[i] == null)
                {
                    items[i].itemName = other.gameObject.GetComponent<ItemProperties>().itemName;
                    items[i].icon = other.gameObject.GetComponent<ItemProperties>().icon;
                    Debug.LogError("Item added!");
                    Destroy(other.gameObject);
                    return;
                }
            }
        }
    }

I literally don’t understand why it says that since I use the object I collided with.

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.

This is the kind of mindset and thinking process you need to bring to this problem:

Step by step, break it down, find the problem.

1 Like

Well this is already a logical error on your side ^^. Your condition is that items should be null. If it is you try to set a property of that null reference, of course you get a NRE ^^. We don’t know what types are stored in your “items” list / array but you probably need to create an instance of that class and store it in that element before you can access something on that object.

1 Like

Alright guys so i got it working. Turns out you should instanciate a object of a class when using, right? :wink:
My Inventory is not completly working by now but if someone is interested I will post the code here.
For now I need to be able to drop items and stack them then I will publish the source code with explanation :slight_smile:

Thanks for all the replies!

Edit:
Here is my inventory. Its not perfect or fully optimized but it works.

This is the main inventory which you add to your player.Here you add all your slots on your ui as well as a empty gameobject that is used to spawn dropped items. You will need to adjust the variables added/removed in this script as well as in the Slot.cs script(coming up) if you add or rename variables in your Items.cs script.Other than that you also have to add your inventory ui to switch it on/off.

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

public class Inventory : MonoBehaviour
{
    public Item[] items = new Item[10];
    public Slot[] slots = new Slot[10];
    public Transform itemSpawn;
    public GameObject ui;
    bool active = false;

    void OnCollisionEnter2D(Collision2D other)
    {
        GameObject temp = other.gameObject;

        if(temp.tag == "Item")
        {
            if (temp.GetComponent<ItemProperties>().stackable == true)
            {
                for (int i = 0; i < 10; i++)
                {
                    if(items[i] != null && items[i].itemName == temp.GetComponent<ItemProperties>().itemName)
                    {
                        items[i].amount++;
                        Destroy(temp);
                        return;
                    }
                }
            }

            for(int i = 0; i < 10; i++)
            {
                if(items[i] == null)
                {
                    items[i] = new Item();
                    items[i].itemName = temp.GetComponent<ItemProperties>().itemName;
                    items[i].icon = temp.GetComponent<ItemProperties>().icon;
                    items[i].stackable = temp.GetComponent<ItemProperties>().stackable;
                    items[i].amount = temp.GetComponent<ItemProperties>().amount;
                    Destroy(other.gameObject);
                    return;
                }
            }
        }
    }

    void LateUpdate()
    {
        if(Input.GetKeyDown(KeyCode.Tab))
        {
            active = !active;
        }

        ui.SetActive(active);

        if (active)
        {
            for (int i = 0; i < 10; i++)
            {
                if(items[i] != null)
                {
                    slots[i].amountText.gameObject.SetActive(true);
                    slots[i].GetComponent<Image>().color = Color.white;
                    slots[i].currName = items[i].itemName;
                    slots[i].icon = items[i].icon;
                    slots[i].stackable = items[i].stackable;
                    slots[i].amount = items[i].amount;
                }
                else
                {
                    slots[i].GetComponent<Image>().rectTransform.sizeDelta = new Vector3(70f, 70f, 70f);
                    slots[i].GetComponent<Image>().color = Color.clear;
                    slots[i].amountText.gameObject.SetActive(false);
                }
            }
        }
    }

    public void AddItem(int index, string name, Sprite icon, bool stackable, int amount)
    {
        items[index] = new Item();
        items[index].itemName = name;
        items[index].icon = icon;
        items[index].stackable = stackable;
        items[index].amount = amount;

        //slots[index].transform.localScale = new Vector3(70f, 70f, 70f);
        slots[index].currName = items[index].itemName;
        slots[index].icon = items[index].icon;
        slots[index].stackable = items[index].stackable;
        slots[index].amount = items[index].amount;
    }

    public void RemoveItem(int index)
    {
        items[index] = null;
        slots[index].currName = null;
        slots[index].icon = null;
        slots[index].stackable = false;
        slots[index].amount = 0;
    }
}

This is the Slot.cs script added to all slots. They will require an Event Trigger with Drag, EndDrag, PointerEnter as well as PointerExit events. On the PointerEnter/PointerExit event click on the little plus symbol and drag the same slot into the field with an Object requirement. Select the dropdown and go (PointerEnter)Slot → OnHover() and (PointerExit)Slot → EndHover().
In the Inventory requirement drag your player. The Items array holds all items that can be picked up so add all item prefabs you want to be collected(and therefore be droped from the inventory) in there. Note that you have to set the case statements in the same order as your items in the array. In the slots array drag the slots from left to right and row down. Your Slots will have to be images that are parents to texts which are used to hold the amount of items that are stacked. This text has to be draged into the amountText field. Ignore the currName and icon if it confuses you you can put a [HideInInspector] over the variables like by the amount or stackable variable.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class Slot : MonoBehaviour, IDragHandler, IEndDragHandler
{
    public string currName;
    public GameObject[] items;
    public Inventory inventory;
    public Sprite icon;
    Vector2 startPos;
    public Slot[] slots;
    public Text amountText;
    [HideInInspector]
    public int amount;
    [HideInInspector]
    public bool stackable = false;
    bool ontop = false;

    void Start()
    {
        startPos = transform.position;
    }

    void Update()
    {
        if (stackable)
        {
            amountText.gameObject.SetActive(true);
            amountText.text = amount.ToString();
        }
        else
        {
            amountText.gameObject.SetActive(false);
        }

        if(ontop && Input.GetKeyDown(KeyCode.Mouse1))
        {
            if (Input.GetButtonDown("Fire2"))
            {
                switch (currName)
                {
                    case "Bandage":
                        Instantiate(items[0], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if(inventory.slots[i] == this)
                            {
                                inventory.items[i].amount--;
                            }
                        }

                        if(amount == 1)
                        {
                            for(int i = 0; i < 10; i++)
                            {
                                if (inventory.slots[i] == this)
                                {
                                    inventory.RemoveItem(i);
                                }
                            }                           
                        }
                        break;

                    case "Bomb":
                        Instantiate(items[1], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if (inventory.slots[i] == this)
                            {
                                inventory.items[i].amount--;
                            }
                        }

                        if (amount == 1)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                if (inventory.slots[i] == this)
                                {
                                    inventory.RemoveItem(i);
                                }
                            }
                        }
                        break;

                    case "Book":
                        Instantiate(items[2], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if (inventory.slots[i] == this)
                            {
                                inventory.items[i].amount--;
                            }
                        }

                        if (amount == 1)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                if (inventory.slots[i] == this)
                                {
                                    inventory.RemoveItem(i);
                                }
                            }

                        }
                        break;

                    case "Clover":
                        Instantiate(items[3], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if (inventory.slots[i] == this)
                            {
                                inventory.items[i].amount--;
                            }
                        }

                        if (amount == 1)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                if (inventory.slots[i] == this)
                                {
                                    inventory.RemoveItem(i);
                                }
                            }
                        }
                        break;

                    case "Feather":
                        Instantiate(items[4], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if (inventory.slots[i] == this)
                            {
                                inventory.items[i].amount--;
                            }
                        }

                        if (amount == 1)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                if (inventory.slots[i] == this)
                                {
                                    inventory.RemoveItem(i);
                                }
                            }
                        }
                        break;

                    case "Gold":
                        Instantiate(items[5], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if (inventory.slots[i] == this)
                            {
                                inventory.items[i].amount--;
                            }
                        }

                        if (amount == 1)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                if (inventory.slots[i] == this)
                                {
                                    inventory.RemoveItem(i);
                                }
                            }
                        }
                        break;

                    case "Mana potion small":
                        Instantiate(items[6], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if (inventory.slots[i] == this)
                            {
                                inventory.items[i].amount--;
                            }
                        }

                        if (amount == 1)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                if (inventory.slots[i] == this)
                                {
                                    inventory.RemoveItem(i);
                                }
                            }
                        }
                        break;

                    case "Mana potion":
                        Instantiate(items[7], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if (inventory.slots[i] == this)
                            {
                                inventory.items[i].amount--;
                            }
                        }

                        if (amount == 1)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                if (inventory.slots[i] == this)
                                {
                                    inventory.RemoveItem(i);
                                }
                            }
                        }
                        break;

                    case "Repairhammer":
                        Instantiate(items[8], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if (inventory.slots[i] == this)
                            {
                                inventory.items[i].amount--;
                            }
                        }

                        if (amount == 1)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                if (inventory.slots[i] == this)
                                {
                                    inventory.RemoveItem(i);
                                }
                            }
                        }
                        break;

                    case "Ring":
                        Instantiate(items[9], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if (inventory.slots[i] == this)
                            {
                                inventory.items[i].amount--;
                            }
                        }

                        if (amount == 1)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                if (inventory.slots[i] == this)
                                {
                                    inventory.RemoveItem(i);
                                }
                            }
                        }
                        break;

                    case "Rope":
                        Instantiate(items[10], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if (inventory.slots[i] == this)
                            {
                                inventory.items[i].amount--;
                            }
                        }

                        if (amount == 1)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                if (inventory.slots[i] == this)
                                {
                                    inventory.RemoveItem(i);
                                }
                            }
                        }
                        break;

                    case "Ruby splinter":
                        Instantiate(items[11], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if (inventory.slots[i] == this)
                            {
                                inventory.items[i].amount--;
                            }
                        }

                        if (amount == 1)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                if (inventory.slots[i] == this)
                                {
                                    inventory.RemoveItem(i);
                                }
                            }
                        }
                        break;

                    case "Ruby":
                        Instantiate(items[12], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if (inventory.slots[i] == this)
                            {
                                inventory.items[i].amount--;
                            }
                        }

                        if (amount == 1)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                if (inventory.slots[i] == this)
                                {
                                    inventory.RemoveItem(i);
                                }
                            }
                        }
                        break;

                    case "Scroll":
                        Instantiate(items[13], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if (inventory.slots[i] == this)
                            {
                                inventory.items[i].amount--;
                            }
                        }

                        if (amount == 1)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                if (inventory.slots[i] == this)
                                {
                                    inventory.RemoveItem(i);
                                }
                            }
                        }
                        break;

                    case "Smaragd splinter":
                        Instantiate(items[14], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if (inventory.slots[i] == this)
                            {
                                inventory.items[i].amount--;
                            }
                        }

                        if (amount == 1)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                if (inventory.slots[i] == this)
                                {
                                    inventory.RemoveItem(i);
                                }
                            }
                        }
                        break;

                    case "Smaragd":
                        Instantiate(items[15], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if (inventory.slots[i] == this)
                            {
                                inventory.items[i].amount--;
                            }
                        }

                        if (amount == 1)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                if (inventory.slots[i] == this)
                                {
                                    inventory.RemoveItem(i);
                                }
                            }
                        }
                        break;

                    case "Stamina potion small":
                        Instantiate(items[16], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if (inventory.slots[i] == this)
                            {
                                inventory.items[i].amount--;
                            }
                        }

                        if (amount == 1)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                if (inventory.slots[i] == this)
                                {
                                    inventory.RemoveItem(i);
                                }
                            }
                        }
                        break;

                    case "Stamina potion":
                        Instantiate(items[17], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if (inventory.slots[i] == this)
                            {
                                inventory.items[i].amount--;
                            }
                        }

                        if (amount == 1)
                        {
                            for (int i = 0; i < 10; i++)
                            {
                                if (inventory.slots[i] == this)
                                {
                                    inventory.RemoveItem(i);
                                }
                            }
                        }
                        break;

                    case "Sword":
                        Instantiate(items[18], inventory.itemSpawn.position, Quaternion.identity);
                        for (int i = 0; i < 10; i++)
                        {
                            if (inventory.slots[i] == this)
                            {
                                inventory.RemoveItem(i);
                            }
                        }
                        break;
                }
            }
        }

        if(icon != null)
        {
            GetComponent<Image>().rectTransform.sizeDelta = GetSpriteSize(icon);
            GetComponent<Image>().rectTransform.sizeDelta *= new Vector2(70f, 70f);
            GetComponent<Image>().sprite = icon;
        }
        else
        {
            GetComponent<Image>().rectTransform.sizeDelta = new Vector2(70f, 70f);
        }
    }

    public void OnDrag (PointerEventData eventData)
    {
        this.transform.position += (Vector3)eventData.delta;
    }
    public void OnHover()
    {
        ontop = true;
    }
   
    public void EndHover()
    {
        ontop = false;
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        for (int i = 0; i < slots.Length; i++)
        {
            if (rectOverlaps(gameObject.GetComponent<RectTransform>(), slots[i].GetComponent<RectTransform>()))
            {
                for (int j = 0; j < slots.Length + 1; j++)
                {
                    if (inventory.slots[j] == slots[i])
                    {
                        inventory.AddItem(j, currName, icon, stackable, amount);
                    }
                }

                for (int j = 0; j < slots.Length + 1; j++)
                {
                    if (inventory.slots[j] == gameObject.GetComponent<Slot>())
                    {
                        inventory.RemoveItem(j);
                    }
                }
            }

        }
        transform.position = startPos;
    }

    bool rectOverlaps(RectTransform rectTrans1, RectTransform rectTrans2)
    {
        Rect rect1 = new Rect(rectTrans1.localPosition.x, rectTrans1.localPosition.y, rectTrans1.rect.width, rectTrans1.rect.height);
        Rect rect2 = new Rect(rectTrans2.localPosition.x, rectTrans2.localPosition.y, rectTrans2.rect.width, rectTrans2.rect.height);

        return rect1.Overlaps(rect2);
    }

    private bool RectOverlap(Rect firstRect, Rect secondRect)
    {
        if (firstRect.x + firstRect.width * 0.5f < secondRect.x - secondRect.width * 0.5f)
        {
            return false;
        }
        if (secondRect.x + secondRect.width * 0.5f < firstRect.x - firstRect.width * 0.5f)
        {
            return false;
        }
        if (firstRect.y + firstRect.height * 0.5f < secondRect.y - secondRect.height * 0.5f)
        {
            return false;
        }
        if (secondRect.y + secondRect.height * 0.5f < firstRect.y - firstRect.height * 0.5f)
        {
            return false;
        }
        return true;
    }

    Vector2 GetSpriteSize(Sprite sprite)
    {
        return new Vector2(
            sprite.texture.width / sprite.pixelsPerUnit,
            sprite.texture.height / sprite.pixelsPerUnit);
    }
}

This is the ItemProperties.cs script it basically only holds the same variables like Item.cs but its used to identify the item not to be used in the data structure like Item.cs

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

public class ItemProperties : MonoBehaviour
{
    public string itemName;
    public Sprite icon;
    public bool stackable;
    public int amount = 1;
}

This is the Item.cs script. it is used internally for structuring the backend. Nothing for you to worry about as long as you don’t change any variables.

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

public class Item
{
    public string itemName;
    public Sprite icon;
    public bool stackable;
    public int amount;
}

Feel free to use and change. You may also want to upload this to the unity assets store. For some reason it won’t do it if I try . . . but anyway I hope it helped!