Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Is it possible to define custom events?

Asked by 6 years ago

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?

1 answer

Log in to vote
0
Answered by 6 years ago

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)
Ad

Answer this question