How do i testfor a item a player is holding? [duplicate]
The SelectedItem
compound holds a copy of the player's currently-held item. If you need to target the player after finding them, you should not use /testfor
because that does not mark matching players for you to target afterwards.
You should instead use a command such as /scoreboard
to assign a label, either a score in pre-1.9 or a "tag" in 1.9+:
/scoreboard players tag @a[tag=HoldingItem] remove HoldingItem
/scoreboard players tag @a[tag=!HoldingItem] add HoldingItem {SelectedItem:{id:"minecraft:diamond_sword",tag:{display:{Name:"Notch's Legendary Sword"}}}}
You would then be able to target the specific players holding the item:
/say @a[tag=HoldingItem]
If it has a custom name you may not need to test for the diamond sword just the custom name: You could use a command like this: /testfor @p[r=1000] {SelectedItemSlot:0,Inventory:[{Slot:0b,tag:{display:{Name:"Notch's Legendary Sword"}}}]}
This will testfor the the player holding the custom named item in slot 0. You may choose to have the radius if you would like.
If you wish to know more watch this video on testfor:
By DragnozThis is a picture of the numbered slots you can use for reference when testing for an item in that slot: