How to tell if a certain item is in a player's inventory, or a specific inventory slot?
I am trying to create a challenge world where a certain item (in my example, a Netherite Sword) must be collected. Using commands, how can I if a player has it, and then run a command, for example, congratulating the winner?
I am also looking for a way to detect these items in a specific item slot. For example, a pair of Netherite Boots should run some commands to give the player the Speed effect when worn.
Is this possible? This question is specific to Bedrock Edition 1.16.
See also: Testing for a certain dropped item
Browse more workarounds for getting/setting NBT in MCBE
22 Answers
You can use /clear<player> netherite_sword -1 0. The -1 matches all data values and the 0 specifies the maximum number of items to clear (so none will be cleared). If the player has at least 1 netherite sword in their inventory, the command will output a success.
The success can be detected using a chain command block. Put the /clear any command block facing a conditional, always active, chain command block with the command that you want to execute if the player has a netherite sword.
Beta answer
This answer describes features that are present in the latest beta, but the full release containing these features has not yet been released.
The latest beta of Minecraft: Bedrock Edition has added a target selector argument, hasitem=.
Syntax is as follows:
One item:
@a[hasitem={ item=<…>, count=<…>, data=<…>, location=<…>, slot=<…> }]Multiple items:
@a[hasitem=[ { item=<…>, ……… }, { item=<…>, ……… } ]]Fields are:
item: Test for which item ID?count: Test for a certain count of this item. Can be a number or range (5..10)data: Test for the item's data value.locationandslot: Only consider the slots specified to look for the item.locationspecifies the slot category,slotspecifies the slot number.
If multiple sections are specified within [ {}, {} ], all must pass.
item, count, data, location, and slot can be repeated within the same section. However, the behaviour of doing so has not been pinpointed.
More is constantly being discovered about hasitem=. This answer will be updated as new discoveries arise.