Minecraft – How to test for an hold item name in Minecraft

minecraft-commandsminecraft-java-edition

I'm trying to make a command block that spawns an item in front of you if you are holding an item with a specific name. I've got these two working scripts;

/testfor @p[r=10] {Inventory:[{tag:{display:{Name:"Item Name"}}}]}

/testfor @p[r=10] {SelectedItemSlot:0,Inventory:[{Slot:0b,­id:"minecraft:diamond_sword"}]­}

but I can't get them together. The block should only look for an item in the active slot.

Best Answer

You can actually combine this into one command. Prior to 1.13, this would look like this:

/testfor @p[r=10] {SelectedItem:{id:"minecraft:diamond_sword",tag:{display:{Name:"Item Name"}}}}

This will return an output if the player is holding a named diamond sword in the selected slot.

However, the above command has been completely deprecated in 1.13. testfor is now Bedrock only, and the [r=] selector has been changed. You also can't really do anything with this testfor anyway, all it does is give a redstone output. A better and updated version for Java Edition 1.13 would be something along the following lines:

/execute at @p[distance=..10, nbt={SelectedItem:{id:"minecraft:diamond_sword",tag:{display:{Name:"Item Name"}}}}] run <your item spawning command>

This command executes <your item spawning command> at the position of a player within 10 blocks that matches the SelectedItem NBT.