How to give tags based on offhand items? Minecraft Java

I want to make it so if you are holding a book if your offhand, you will receive a tag, but if the book is not in your offhand, you dont have the tag anymore, how do I do this with command blocks?


Solution 1:

To apply the tag when the player is holding a book, it's easy:

tag @e[nbt={Inventory:[{Slot:-106b,id:"minecraft:book"}]}] add testTag

To remove it when the player is not holding a book, use the /execute command to tell each player to check their NBT for a book in their offhand, and remove the tag if it is not found.

execute as @a unless entity @s[nbt={Inventory:[{Slot:-106b,id:"minecraft:book"}]}] run tag @s remove testTag