Minecraft – Clearing just one item in a specific hotbar slot

minecraft-commandsminecraft-java-edition

I'm making a little thing for my friends that when you swap a redstone dust to your offhand hotbar you get an effect for 10 seconds, but if you swap 2 at the same time you get 20 seconds, and so on. However, if I want to achieve this, I'll have to clear them one by one, which replaceitem doesn't seem to do, and if I do that it will clear any of the same item in my inventory NOT in my offhand first. How would one use /clear to remove just one item from a specific slot, say, the offhand slot in the inventory? Is it possible? If it's not possible, is there any other workaround? I'm trying not to make is so you can't stack these redstones.

Thanks in advance for any help.

Best Answer

I figured it out with MBraedley's help. First I have to tag the player with "redstone".

tag @a[nbt={Inventory:[{Slot:-106b,id:"minecraft:redstone"}]}] add redstone

Then I need to use the execute with store to see how many redstones I have...

execute as @a[tag=redstone] store result score @s check1 run clear @s redstone 0

Then I have to use replaceitem to get rid of all the redstones in my offhand...

replaceitem entity @a[tag=redstone] weapon.offhand air

Then I have to subtract my second score by my first score, and the resulting negative number will by how many redstones I got rid of times -1.

execute as @a[tag=redstone] store result score @s check2 run clear @s redstone 0

scoreboard players operation @a[tag=redstone] check2 -= @s check1

Then I just remove the redstone tag. I had to use a tag because there are commands that come after when I clear the redstones from my offhand so I couldn't detect the player using -nbt=...].

Thanks again MBraedley!

EDIT: Just realized that last scoreboard command only finds the correct number of used redstones for some equations like 1 - 2, but not for some like 1 - 4, which would suggest I used 3. The solution is to deplete both scores of the player until one score is 0, and the other will be the answer times 1. To do that, remove the player of score check1 64 if his score is 64 or above (start at 64 because one cannot have more than 64 items in his hotbar), then remove 32 if he has above 32, and so on, and for each removal you remove the same amount for check2.

Related Topic