Using a command to test when a player eats something [duplicate]

Is there some kind of command that I could use to test when the player eats something, then after the player has eaten that thing, give them 2 hearts? I have a feeling it might be a testfor command....


Solution 1:

Similarly to how you might prevent someone from using a diamond sword, the easiest way of doing this in vanilla is to use scoreboards. Unfortunately, there is no way to check for all foods with a single scoreboard objective; you'll have to set up an objective for each food item. Additionally, there was a bug in previous versions that prevents doing what you asked, and you'll need to use 1.8 snapshots or later.

For this example, I'll use bread, but you need to cover each food item. First set the scoreboard objectives for each food type to be tracked:

/scoreboard objectives add ateBread stat.useItem.minecraft.bread

You don't need to do this from a command block, any op can run the command.

Next, for each food item, you'll need a pair of command blocks, with the first of the pair feeding into the second with a comparator. The first looks for players that have eaten a food item, and gives them 2 hearts (4HP), the second resets those players scoreboard objective for that food item:

effect @a[score_ateBread_min=1] 6
scoreboard players set @a[score_usedBread_min=1] usedBread 0

Finally, hook all the command block pairs to a fast clock, and you're set.

Now there are some drawbacks here. First, if their hunger bar is full, they won't be able to eat, and thus won't be able to regenerate using this method. Second, again if their hunger bar is full (or nearly full), they'll regenerate naturally, which may not be the desired outcome. The following video provides a way around this, and will also set up everything from a single command block.

It does a few things differently than what I'm showing above, but the end result is the same.