Question about InventoryUI Redraw When Add or Remove Item

In The InventoryUI.cs, there is a method called Redraw and it is been called when there is add or remove or load from the inventory. Besides The loading method which requires drawing the entire inventory, I wonder if it will be more efficient if the code can redraw the specific slot only when adding or removing by passing in the index?

I know we only have 16 slots and even if the number gets to 1000 I don’t think the performance will impact a lot, just wonder which is the best to implement.

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;
        }
2 Likes

This makes sense and I totally agree that redrawing the entire inventory will be way easier than doing an update on a single inventory slot. I just start learning unity and I do not see any performance issues if we redraw the entire inventory.

Maybe in the future, I will come back to this topic if I start learning to make multi-player games. Thanks for your answer!

Privacy & Terms