Minecraft – Decrease Stack Size in Chest

minecraft-commandsminecraft-java-edition

I'm trying to make a custom crafting system in minecraft with command blocks, and for this when someone puts in a correct recipe, it should give them the result and take one item out of each of the slots. There seems to be now way to easily remove just one item from a slot in a chest, and the only way I can think of is to detect if it is a certain stack size and put in that stack size minus one, but I would have to do that for every item because there seems to be no way to replaceitem to just modify the stack size and not the item

What I need: Something similar to

/replaceitem block x y z slot <keep item the same> ammount <keep data the same> <keep datatag the same>

or even to just be able to decrease the ammount of an item in slot x of a chest

Is there a way to replaceitem without changing the item or otherwise decrease the stack size of an item in a chest?

Best Answer

This is possible somewhat easily since 1.13 thanks to /execute store.

As a preparation, you need some scoreboard:

/scoreboard objectives add temp dummy

Then you need the value 1 somewhere. Here I set it for the dummy player #1 (which can't be a real player name and does not appear in scoreboard displays):

/scoreboard players set #1 temp 1

When you actually want to decrease the item count, first store the amount in a scoreboard:

/execute store result score @s temp run data get block ~ ~ ~ Items[{Slot:0b}].Count

I specifically check for Slot:0b instead of simply using the index (Items[0]) as a workaround of a bug.

Now you need to subtract 1:

/scoreboard players operation @s temp -= #1 temp

And store it back to the chest's NBT.

/execute store result block ~ ~ ~ Items[{Slot:0b}].Count byte 1 run scoreboard players get #1 temp