How to detect if a player took damage

Ello, this is my first post here.

So, I’ve been working on a game for some weeks, and I decided to do a damage effect GUI. But, I need to know if a player took damage. I already tried to use ‘Humanoid:GetPropertyChangedSignal(‘Health’)’ but it detect if health is changed [ if got healed or damage ]. Someone can help me?

-Tsu.

13 Likes

The HealthChanged event of the Humanoid allows you to determine how much the health changed from its previous value, which can be used to make sure that you only apply that effect when they’ve taken damage.

Example:

local Players = game:GetService("Players")
local player = Players.LocalPlayer

local function CharacterRespawned(Character)	
	local Humanoid = Character:WaitForChild("Humanoid") -- Redefines the Humanoid whenever the Character respawns
    local oldHealth = Humanoid.Health -- This will reference the Humanoid's Health before it updates

	Humanoid.HealthChanged:Connect(function(newHealth)
        local healthDifference = newHealth - oldHealth
        if newHealth < oldHealth then -- If the Humanoid's new Health is less than the old Health, then we know that the player's Character has taken damage
            warn(player.Name.." has taken "..(math.abs(healthDifference)).." damage")
        end

        oldHealth = newHealth -- Updates the "oldHealth" variable to the current Health so that it can be compared the next time it changes
    end)
end

if player.Character then
	CharacterRespawned(player.Character)
end

player.CharacterAdded:Connect(CharacterRespawned)

Post Edits Changelog

Edit (May 20th, 2022) – Updated the Roblox Developer Hub Documentation links throughout this post to the new Creator Documentation pages.

Because the Roblox Developer Hub will be superseded by Roblox’s Creator Documentation, I figured that it would be better to replace the links in this post sooner rather than later so that the main post wouldn’t have broken links in the far future.

Before

HealthChanged - Developer Hub Documentation

After

HealthChanged - Creator Documentation

3 Likes

Have you looked at this?

I believe there’s a code sample that detects if the health increases or decreases

1 Like

Hum, I’ll try doing the script using that.

hey, i’ve tried my best to help you. here’s my code

local Humanoid = game.Players.LocalPlayer.Character.Humanoid
local OldHealth = Humanoid.Health

Humanoid:GetPropertyChangedSignal("Health"):Connect(function()
if Humanoid.Health < OldHealth then
	print("damage taken")
end

OldHealth = Humanoid.Health
end)

(also, this should be in a local script in startercharacterscripts. if you werent looking for a client sided way of doing so or this doesn’t work please let me know and i’ll try my best to help. feel free to manipulate this code in any way)

21 Likes

You would simply use a HealthChanged event.

1 Like

Thanks, that helped me a lot buddy.

1 Like

no problem, man! have a nice day and I hope your game/project goes well.

4 Likes