Minecraft – Why does the /execute as command not work

minecraft-commandsminecraft-java-edition

For my Minecraft map I have decided that when a player holds this sword he will gain speed 2 but it seems that it doesn't detect when I am holding the item.

This is the command I used:

/execute as @a[nbt={SelectedItem:[{Slot:0b,id:"minecraft:iron_sword",tag:{display:{Name:"{\"Kurikara\":\"\"}"}}}]}] run say hey

The command itself isn't highlighted red saying there is an error, but when it comes to actually detecting my item it never runs the command /say so i think something is wrong elsewhere in the command.

Best Answer

  1. SelectedItem is not a list. Remove the square brackets ([]).
  2. SelectedItem does not store a slot number, it's handled itself similarly to a slot. You can always check things like this easily with "/data get entity @s SelectedItem". If you really want to check if this specific item is selected AND in the first hotbar slot, then you can additionally check for "SelectedItemSlot:0" (yes, this is an integer, not a byte). But usually it's more convenient for the player if you don't have this restriction.

An alternative to what you're doing is called "Attributes". With those, you don't need any commands running permanently, you can just edit the player's "generic.movementSpeed" attribute directly with the sword.
Here is the wiki page for this: https://minecraft.gamepedia.com/Attribute (archive)