How to track the use of a named/enchanted item using a scoreboard (or otherwise) in Minecraft? [duplicate]

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.


Solution 1:

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.

Solution 2:

To combine the two dataTags you need to move the tag compound from first command into the inventory item compound in the second:

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

Note: This will only test true if the item is in slot 0 and it is also the selected item.

You can use the SelectedItem tag instead of the SelectedItemSlot tag. This will allow you to target any player who currently has the specified item selected no matter which slot it is in:

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

As of 1.9 you can use scoreboard add tag command to tag the player holding the specific item.

scoreboard players tag @a add <tagName> {SelectedItem:{id:"minecraft:diamond_sword",tag:{display:{Name:"Item Name"}}}}

This allows you to target the players within another command. Lets make the players with the selected sword say hello:

/execute @a[tag=<tagName>] ~ ~ ~ say hello

You could use this tag in the item summon commands.

Then to remove the tag from all player:

scoreboard players tag @a remove <tagName> 

If you want to test for any player holding any item with the correct name, simply omit the id portion of the dataTag:

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