You’re not using the course InventoryUI, you’re using a version I wrote for filtering by type for another student. Unfortunately, this filtering system does not mix with not destroying and re-instantiating the inventory slots, because the number of inventory slots that needs to be drawn changes in every change of the Inventory… Are you actually using the filter? It’s likely the filter that is the driving force in the lag spike.
This is the original code from the Inventory course:
private void Redraw()
{
foreach (Transform child in transform)
{
Destroy(child.gameObject);
}
for (int i = 0; i < playerInventory.GetSize(); i++)
{
var itemUI = Instantiate(InventoryItemPrefab, transform);
itemUI.Setup(playerInventory, i);
}
}
Refactoring to avoid destroying the InventorySlotUI works like this:
private int inventorySize = -1;
private void Redraw()
{
if (inventorySize == playerInventory.GetSize())
{
for (int i = 0; i < inventorySize; i++)
{
transform.GetChild(i).GetComponent<InventorySlotUI>().Setup(playerInventory, i);
}
return;
}
inventorySize = playerInventory.GetSize();
foreach (Transform child in transform)
{
Destroy(child.gameObject);
}
for (int i = 0; i < playerInventory.GetSize(); i++)
{
var itemUI = Instantiate(InventoryItemPrefab, transform);
itemUI.Setup(playerInventory, i);
}
}