The last two days I have been busy with refactoring and moving code from Blueprint to C++. Today I realised that I finally had to implement methods to remove items from my inventory component.
A while back I decided to implement a slot based inventory system that can contain stacks of items if they are set to be stackable. The inventory system is implemented as an ActorComponent and can thus be attached to every Actor in the game. I don’t know if this is the preferred way to implement such a system in Unreal, but I’m happy with how it works at the moment.
The functionality to remove items is of course essential and I need it to remove items once they are equipped by the player or consumed/used.

There are two methods that can be used to remove items in the inventory at this time. One that removes a certain instance of an item and one that removes an specified amount of an item type.
bool UInventory::RemoveInstance(UItemInstance* Instance)
{
FInventorySlot Slot;
if (!FindSlotOfInstance(Instance, Slot))
return false;
this->Slots[Slot.SlotIndex].Free();
TArray<int32> ChangedSlots;
ChangedSlots.Add(Slot.SlotIndex);
SlotsRefreshed.Broadcast(ChangedSlots);
return true;
}
This methods as mentioned before takes care of freeing the entire slot that is occupied by the passed Item Instance. An Item Instance is a wrapper that I will be using to save per instance data for an item in the inventory (for example durability, generated stats etc.).
bool UInventory::RemoveItem(UItem* Item, int32 Count)
{
....
TArray<int32> ChangedSlots;
FoundSlots.Sort([](const FInventorySlot& LHS, const FInventorySlot& RHS)
{
return LHS.GetStackSize() < RHS.GetStackSize();
});
int32 i = 0;
int32 Index = FoundSlots[i].SlotIndex;
bool HasBeenRemoved = false;
while (Count > 0)
{
....
}
if (HasBeenRemoved)
{
SlotsRefreshed.Broadcast(ChangedSlots);
}
return HasBeenRemoved;
}
This method can be called whenever I want to remove not a specific instance but an amount of items. I omitted some of the code from the sample to shorten the code.
First of all I sort the list of slots I found that hold the passed UItem. I sort it by StackSize in order to start removing items from the lowest stack found. Afterwards I iterate over the Count till it reaches zero and I removed all items from the inventory. The SlotsRefreshed array contains all the indices that changed which will be broadcasted to subsystems (such as the UI).
