Add bool check for OnPointerClick

Hello, i have this script for inventory slot

    public void OnPointerClick(PointerEventData eventData)
    {
            InventoryItem inventoryItem = eventData.pointerDrag.GetComponent<InventoryItem>();
            //itemIndex = System.Array.IndexOf(inventorySlots, inventoryItem);
            inventory.AddItemToToolbar(inventoryItem.item);
            inventory.RemoveItem(inventoryItem.item);
    }

If item in inventory slot it works fine, but if there is no item, it gives null reference error. How do i add check if slotisfull?

Just do a null check(s) inside the method.

I found solution

if (transform.childCount == 1)
{
}

Hey i tried against null check still getting null reference error, when i click on empty space.
at line

 InventoryItem inventoryItem = eventData.pointerDrag.GetComponent<InventoryItem>();
    public void OnPointerClick(PointerEventData eventData)
    {
        InventoryItem inventoryItem = eventData.pointerDrag.GetComponent<InventoryItem>();
        if (inventoryItem != null)
        {
            if (inventoryItem.item.type == ItemType.Laser)
            {
                inventory.AddItemToToolbar(inventoryItem.item);
                inventory.RemoveAt(SlotIndex);
            }
        }
    }

Then figure out where the null reference is coming from and guard against that.

The first thing you must do with a null-reference error is debug where the actual null is coming from. You can’t start to fix it until you know what is null.

1 Like

Figured it out!

    public void OnPointerClick(PointerEventData eventData)
    {
        if (eventData.pointerDrag != null)
        {
            InventoryItem inventoryItem = eventData.pointerDrag.GetComponent<InventoryItem>();
            if (inventoryItem != null)
            {
                if (inventoryItem.item.type == ItemType.Laser)
                {
                    inventory.AddItemToToolbar(inventoryItem.item);
                    inventory.RemoveAt(SlotIndex);
                }
            }
        }
    }
1 Like