What is the correct way to Update a stack quantity

Zaddo

Active member
The API examples demonstrate how to add and remove items from the inventory, but I couldn't find any examples showing how to update the quantity of an existing stack.

What is the correct way to update the quantity of a stacked item?

I've been using AddItem/RemoveItem from the item collection, as well as ItemStackutil.SetAmount in different scenarios. However, I've encountered edge cases that led to bugs in my project.

Through testing, I found that Option 1 below works best. Option 2 causes issues with equipping mutable non-unique items in the hotbar, I can no longer equip them if I update the quantity this way.

Is Option 1 a valid solution?

I've noticed that I must always call UpdateCachedInventory on the inventory after using either option. Otherwise the inventory quantities don't update correctly, and if I try to craft using these items, the crafting engine see's the previous quantity. Is this the correct approach?


//Option 1
ItemStackUtil.SetAmount(itemInfo.ItemStack, qty);

// Option 2
if (qty < itemInfo.ItemStack.Amount)
itemInfo.ItemCollection.RemoveItem((itemInfo.ItemStack.Amount - qty, itemInfo));
else
itemInfo.ItemCollection.AddItem((qty - itemInfo.ItemStack.Amount, itemInfo), itemInfo.Stack);
 
Last edited:
Adding and removing items should be correct.
You should never have to directly change ItemStack amounts. This would bypass a lot of events which in turn might cause issues down the line.

I don't remember coding a public ItemStackUtil class. Is this something you added yourself?

In any case, you should go with whatever works best for you, but just be careful that you aren't skipping over some important events
 
Adding and removing items should be correct.
You should never have to directly change ItemStack amounts. This would bypass a lot of events which in turn might cause issues down the line.

I don't remember coding a public ItemStackUtil class. Is this something you added yourself?

In any case, you should go with whatever works best for you, but just be careful that you aren't skipping over some important events
Thanks.
The ItemStackUtil.SetAmount, just calls SetAmount on the ItemStack. Apologies, I meant to post this.
 
Back
Top