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?
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.
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)