How do i run a minecraft datapack function when a player has a specific item in their inventory? (minecraft 1.15)



  • I'm making a datapack and in it I need to check (in a mcfunction file) if any player (@a) has a specific item in their inventory (minecraft:gold_ingot{coin:1}) if so, I need to run a function (gc:coin_amount). In-game I have used conditional command blocks to achieve this (execute as @a run clear @s minecraft:gold_ingot{coin:1} and then function gc:coin_amount), however I have no idea how to pull it off inside a mcfunction file in a datapack.

    Any help would be appreciated.



  • You can store the result of a command with /execute store. In this case:

    /execute as @a store result score @s gold run clear @s gold_ingot{coin:1}
    

    Then you can use that score for whatever you want. In this case you're just interested in whether it's 1 or more:

    /execute as @a if score @s gold matches 1.. run 
    

    As a nice side effect, this also runs the function as every player who matches that condition. If you don't want that, use /execute if entity @a[scores={gold=1..}] run instead.

    Also, if you just want to check whether someone has an item (or how much of it), without actually taking it away, use the /clear command with a count of 0.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2