I'd like an event to fire when a Humanoid's Health is decreased. Currently I am using the HealthChanged event, but this also fires when Health increases. Is there a method that I can use to define my own HealthDecreased event?
Is it possible to define custom events?
1 answer
It is possible and very easy to create your own custom events
Rather than writing a long answer centered around how to write your own Signal class, Ozzypig describes the process in great detail in his blog right here.
Instead of solving your question of how to create custom signals, I'll solve your current and immediate problem, how to detect if the health of a Humanoid decreases.
Like you pointed out, the Humanoid's HealthChanged event fires both when the health increases and decreases, the problem is that we need to detect only when it decreases.
This is actually a rather easy fix. We know that for their health to have decreased, their previous health had to be higher. PreviousHealth > CurrentHealth
local Character = ...
local Humanoid = Character:WaitForChild("Humanoid")
local PreviousHealth = Humanoid.Health
Humanoid.HealthChanged:Connect(function(CurrentHealth)
if PreviousHealth > CurrentHealth then
print("Health decreased.")
end
PreviousHealth = CurrentHealth
end)
This discussion is preserved as it was. New answers, comments, and votes are closed.
