Minecraft – How to use a command block to detect if a slot in the inventory is empty

minecraft-commandsminecraft-java-edition

I'm trying to make a cool minigame.
How do I make it where when you throw a snowball and when your inventory slot [for the snowballs] is empty, it gives you another one.

Best Answer

You cannot do it directly with NBT detection because the slot simply does not exist when empty. What you can do instead is initially label the player as having the slot empty first, and then remove the label if they actually do have a snowball in that slot.

For example, the following would be run in the presented order, assuming a dummy objective called "NoSnowball" was created:

  1. Label them as having no snowball.

    /scoreboard players set @a NoSnowball 1
    
  2. Change their score to 0 if they actually do have a snowball in Slot 0.

    /scoreboard players set @a NoSnowball 0 {Inventory:[{id:"minecraft:snowball",Slot:0b}]}
    

Players with a resulting score of 1 did not have a snowball in slot 0:

/give @a[score_NoSnowball_min=1] minecraft:snowball

For 1.9+, you can use scoreboard tags instead of requiring an objective.

  1. Apply label by default.

    /scoreboard players tag @a[tag=!NoSnowball] add NoSnowball
    
  2. Remove the label if they do have a snowball in slot 0.

    /scoreboard players tag @a[tag=NoSnowball] remove NoSnowball {Inventory:[{id:"minecraft:snowball",Slot:0b}]}
    

Players that still have a "NoSnowball" tag will be those without snowballs in slot 0.

/give @a[tag=NoSnowball] minecraft:snowball