How to detect a mobs health, on Java 1.17
Matthew Barrera
Simple as it is, I'm trying to make a boss fight for a game I'm making, and I'm trying to execute a different phase when the Boss hits a certain health.
I know that I need to create a scoreboard, but I don't know what kind and how to detect the health to trigger an event. Please help thanks!
2 Answers
You can get the health of any entity by using the /data command. Try it on yourself:
data get entity @s HealthIf you are at full health, you should see "ginkgo has the following entity data: 20.0f". If you have taken some damage, you might see "ginkgo has the following entity data: 18.44835f".
This alone is already enough to detect health, for example—you can detect when your player is at full health:
execute if entity @s[nbt={Health:20.0f}] run say I am fully healed!Or your player is at exactly half health:
execute if entity @s[nbt={Health:10.0f}] run say I am at exactly half health. Not a fraction above or below!The only issue is that in this format, it is difficult (if not impossible) to detect if an entity is within a certain Health range. To test for a range, we need to convert the Health into a format that can be tested easily: scores.
Using the execute store result score command, we can store the Health of an entity onto a scoreboard. To do so, we will use a dummy scoreboard.
scoreboard objectives add Health dummyNow, we can store our Health onto the dummy scoreboard:
execute store result score @s Health run data get entity @s HealthIf you use /scoreboard objectives setdisplay sidebar, you can view your Health on the sidebar. If you take some damage, you might notice that your Health is always listed as a whole number instead of a decimal like before (18.44835f). This is because scoreboard values are stored as integers, which can only be a whole number. It will truncate any decimal values (? i think). This will not really matter for your purposes, anyways.
Now that your Health is stored in scoreboard form, we can easily test for a range:
execute if score @s Health matches ..10 run say I am under half health! Ginkgo's answer works perfectly, just make sure to execute the last command as the entity you are targeting.
Set up the scoreboard by entering this once:
scoreboard objectives add health dummyThen put the following 2 commands into repeating command blocks:
execute as @e[] run execute store result score @s health run data get entity @s Health
execute as @e[] run execute if score @s health matches 10..20 run say I have 10-20 hp!