This is actually an optimization I’m considering myself, as there is quite a garbage collection problem with the way we are currently handling things…
So here’s my idea:
We’ll start with an event in Inventory.cs
public event System.Action<int> onSlotUpdated;
Then in both AddItemToSlot and AddToFirstEmptySlot, comment out the section calling inventoryUpdated and instead add
onSlotUpdated?.Invoke(i); //use i in AddToFirstEmptySlot and slot in AddItemToSlot
Finally, in InventorySlotUI, we’ll subscribe to the event we’ve created
public void Setup(Inventory inventory, int index)
{
this.inventory = inventory;
this.index = index;
inventory.slotUpdated += UpdateItem;
icon.SetItem(inventory.GetItemInSlot(index), inventory.GetNumberInSlot(index));
}
private void UpdateItem(int slot)
{
index = slot;
icon.SetItem(inventory.GetItemInSlot(index), inventory.GetNumberInSlot(index));
}
One last detail in InventorySlotUI… we need to unsubscribe from the event.
private void OnDestroy()
{
if (inventory != null) inventory.slotUpdated -= UpdateItem;
}