0

I want to use command blocks to give a player an item (in this case cgm:advanced_bullet) every time they run out of that same item.

I've tried using this series of commands:

execute as @a if data entity @s {Inventory:[{id:"cgm:advanced_bullet",Count:0b}]} run tag add @s ammoRefill

give @a[tag=ammoRefill] cgm:advanced_bullet 64

tag remove @a[tag=ammoRefill] ammoRefill
1
  • 1
    There is no item with stack size 0. Try execute unless without Count instead. Aug 1, 2023 at 22:37

1 Answer 1

1

The inventory doesn't store item stacks that don't exist, so you won't be able to find them in the player data. There is a way to do what you want with data checks, but first I'm going to show you a much better way of doing this.

Accessing block NBT or entity NBT is very slow in commands, because Minecraft has to convert the full entity / block into NBT every time you do it (and back again, if you're editing the data). If you can avoid it, your commands will cause much less lag. Fortunately, you can in this case.

The faster option: clear and execute store

Every command in Minecraft can return a "result" number when it's run. Not every command's result is useful, but some are very handy.

For /clear, the result is the number of matching items in the player's inventory. Note: it's not the number of items that were actually cleared, but the number of items that were found! So if you do clear @s cgm:advanced_bullet 0, the 0 will stop the command from removing any items, but the result will still be the number of cgm:advanced_bullets in your inventory.

Using the store subcommand of execute, we can store a command's result into a score. Like so:

execute as @a store result score @s heldBullets run clear @s cgm:advanced_bullet 0

This command will give every player a score equal to the number of cgm:advanced_bullets in their inventory. Just run /scoreboard objectives add heldBullets dummy in the chat to set up the scoreboard objective.

Your full set of commands can be:

execute as @a store result score @s heldBullets run clear @s cgm:advanced_bullet 0

give @a[scores={heldBullets=0}] cgm:advanced_bullet 64

Find how many bullets each player has, and then give them more if it's zero.

The slower option: NBT

But to fully answer your question, this can be done with NBT. (It's just less efficient.) You need to check that the player doesn't have any stacks of cgm:advanced_bullet, rather than that they do have stacks of size zero.

give @a[nbt=!{Inventory:[{id:"cgm:advanced_bullet"}]}] cgm:advanced_bullet 64

This gives the items to any player who doesn't have a stack of bullets. But even though it's a single command, the NBT access makes it slower than the two commands above. I recommend going with the /clear method.

1
  • Thanks a ton! I used what you told me and turned it into a data pack using a function.
    – N_Dracorex
    Aug 2, 2023 at 2:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .