Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

made a script that should print something when ever player has taken damage (dosen't work?)

So i made this script that will (for now) print something when player has taken damage. But it wont work! why?

local hum = game.Players.LocalPlayer.Character.Humanoid
local currHealth = hum.Health
 
hum.HealthChanged:connect(function(h)
    if h.Health == h.Health -5 then
print "damage dealed"
 
    end
end)

3 comments

0

its that deprecated Connect you used.

0

No it isn't - deprecated doesn't mean "Broken".

0

i thought it meant "it was a joke".

2 answers

Humanoid.Health is the current health of the humanoid. Humanoid.Health - 5 is the current health of the humanoid subtracted by 5. The humanoid's health is always equal to itself, therefore, your if statement will never go through.

This is code from https://developer.roblox.com/api-reference/event/Humanoid/HealthChanged

local humanoid = game.Players.LocalPlayer.Character.Humanoid
local currentHealth = humanoid.Health
humanoid.HealthChanged:Connect(function(health)
	local change = currentHealth - health
	print("The humanoid's health "..(currentHealth > health and "decreased by " or "increased by ")..change..".")
	currentHealth = health
end)

If you want to to check if 5 damage was taken to the humanoid, simply check if (currentHealth - health) == 5

1 comment

0

Comparing a value with the same value will always equal to itself. It's redundant.

You're comparing a number to itself minus 5, rather than comparing your previously saved current health.

Also, don't use == when dealing with decimal values. It will only work if the decimal values are exactly the same to every decimal point, and due to the way computers work with decimals, they probably won't be.

local hum = game.Players.LocalPlayer.Character.Humanoid
local currHealth = hum.Health

hum.HealthChanged:connect(function(h)
    -- Need to compare to currHealth, and need to use < rather than ==
    if h.Health < currHealth -5 then
        print("damage dealed")
        -- update current health for next check
        currHealth = h.Health
    end
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.