How can I add a count to this command: [duplicate]
Solution 1:
Firstly, commands ran with run_command
in JSON run as if the person who clicks on it typed it into chat, that's why you need a /
at the beginning and it outputs it as a chat message otherwise and that also means that it runs with the same permissions level as the player. So you need to setup a trigger scoreboard:
/scoreboard objectives add ironTrigger trigger
/scoreboard players enable @a ironTrigger
And the corresponding part of the tellraw
command becomes:
{"text":"Iron","clickEvent":{"action":"run_command","value":"/trigger ironTrigger"}}
You can also use /trigger ironTrigger <number>
, in case you want to use that number for e.g. the number of iron ingots later.
To keep the trigger active all the time, you can put scoreboard players enable @a ironTrigger
and scoreboard players set @a ironTrigger 0
into a repeating command chain.
Then you need to check if the player has at least 20 iron ingots. Since you want to clear them anyway, you could just do /clear @p[scores={ironTrigger=1..}] iron_ingot 20
, but that would also clear for example 10 ingots if there are just 10. You only want to clear 20 or none, so you need to check how many items there are. Ironically, that is done with /clear
as well (needs /scoreboard objectives add ironIngots dummy
before first use):
/execute as @a[scores={ironTrigger=1..}] store result score @s ironIngots run clear @s iron_ingot 0
This removes 0 iron ingots from your inventory, which might seem useless, but the command returns as its result
value the number of iron ingots in your inventory. This can then be stored in a scoreboard with /execute store result
.
And then, finally, actually clear the items if there are enough:
/clear @a[scores={ironIngots=20..}] iron_ingot 20