Remove Item from inventory for loop;

   public void RemoveItem(ItemSO item)
   {
       for (int i = 0; i < inventorySlots.Length; i++)
       {
           InventorySlot slot = inventorySlots[i];
           InventoryItem itemSlot = slot.GetComponentInChildren<InventoryItem>();
           if (itemSlot != null)
           {
               Destroy(itemSlot.gameObject);
           }
       }
   }

How do i change this function to remove item from selected slot. Right now it removes all items.

You need to actually check that the slot has the item you are trying to remove.

Rough example:

public void RemoveItem(ItemSO item)
{
    foreach (var slot in inventorySlots)
    {
        InventoryItem itemSlot = slot.GetComponentInChildren<InventoryItem>();
        if (itemSlot != null)
        {
            ItemSO slotItem = itemSlot.Item;
            if (slotItem == item)
            {
                Destroy(itemSlot.gameObject);
                break; // potentially not required
            }
        }
    }
}

Also your InventorySlot component should just expose a reference to a potential inventory item, rather than requiring a GetComponentInChildren call.

In the end it’s about creating our own API that works for you.

1 Like

Still removes all items from inventory with this code :disappointed:

What did you change? Did you debug it? Check why its removing all if you dont think it should

It wasn’t about copying my code it was about showcasing a concept. You need to create a condition in which, when passed, will remove the item from the inventory.

If it’s not working, you need to debug it.

Its working, but removing all items.

Dude you are lifesaver, i removed break, with break it works!

Can you explain why it works with break and remove all without break?

Hey, i have a little problem, it always removes items in order from 1st slot to 2nd to 3rd etc. How do i make it remove item from selected slot?

Yes as written it would only remove the first matching item it finds.

If you want to remove from a specific slot, you need to introduce a means of picking a specific slot then removing the item from said slot. This is functionality you need to introduce yourself.

How do i make picking slot function, can you help, please?

Or lets say, how do i make it remove from last slot?

Then make it loops backwards instead.

Can i somehow get index of array from IPointerClick?