How to make a command block run a command once another one stops running [duplicate]

I am trying to make a system to where there is a command block that sets the health of a player to 1 heart while they are wearing a certain helmet, and then sets it back to 10 hearts when they take the helmet off.

I have solved the system of how to detect if the helmet is on and setting the health as such, but I fall short on how to reset the health once the helmet is removed

The command I am running right now is:

/execute as @p[nbt={Inventory:[{Slot:103b,id:"minecraft:player_head",Count:1b,tag:{DivingHelmet:1b}}]}] run attribute @p minecraft:generic.max_health base set 2

I am playing Java 1.16.5


Solution 1:

DisplayNameNotFound's answers should work, but they are considering there won't be any other command that affects your health. For example another helmet that sets your health to 5 hearts. It would check if the helmet of 5 hearts is on (Lets say yes, it is) so it sets to 5, then checks if the one with 1 heart is (no, it isn't) so it sets back to 10.

My solution will be to create a scoreboard to track which helmet is on, and set the health accordingly: ( in the command can be changed to whatever name you wish)

/scoreboard objectives add helmet dummy

Note: Your execute command is wrong, as it will only look for the closest player to the command block and change their health. So if you have more than one player, the command will choose only one to update their health at a time. I'll be fixing it here.

  1. First, we will set out scoreboard to 0, so on every cycle it starts at 0.
  2. Then, we will test if the player's score is 0, and we will use your command to test for the player's helmet and, instead of setting their health, we will give them a score (can be whatever we want, i'll use the health they will give as the score)
  3. If the score is X (the above one) we will give them X health
  • For another item, repeat step 2 and 3
  1. Finally, test if the player has their score set to 0, then we set their health to 10

Here it is translated to commands (order doesn't matter, except for step 1 and 4):

/scoreboard players set @a helmet 0
/execute as @a if score @s helmet matches 0 if entity @s[nbt={Inventory:[{Slot:103b,id:"minecraft:iron_helmet"}]}] run scoreboard players set @s helmet 1
/execute as @a if score @s helmet matches 1 run attribute @s minecraft:generic.max_health base set 2
/execute as @a if score @s helmet matches 0 run attribute @s minecraft:generic.max_health base set 20

I didn't put anyother "helmet" there since you didn't ask. Those 4 should be enough for your problem and possibly future problems.