Script working late

repeat wait() until script.Parent.Humanoid.Health < 1

script.Parent.NPCMOVEMENT:Destroy()

script.Parent:Destroy()

this simple script works but it works late. The NPCs health becomes lower than 1 but it fires late.

That’s truly a bad habit, please consider using HealthChanged event of the humanoid instead, make sure it is a you connect it to a variable so you can disconnect it

local HealthChangedEvent = script.Parent.Humanoid.HealthChanged

HealthChangedEvent:Connect(function()
    if script.Parent.Humanoid.Health < 1 then
        script.Parent.NPCMOVEMENT:Destroy()
        HealthChangedEvent:Disconnect()
    end
end)
4 Likes

First, use the script that @BasedKnowledge mentions. Second, only destroy the parent and not both parent and child. If you destroy the parent, all its childs are also destroyed

local HealthChangedEvent = script.Parent.Humanoid.HealthChanged

HealthChangedEvent:Connect(function()
    if script.Parent.Humanoid.Health < 1 then
        script.Parent:Destroy()
        HealthChangedEvent:Disconnect()
    end
end)

Credit to @BasedKnowledge of course.

1 Like

HealthChanged has a parameter, which is the new value of Humanoid.Health.
You can use that instead.

Reference: https://developer.roblox.com/en-us/api-reference/event/Humanoid/HealthChanged

2 Likes