So I am making a custom health regen system. I want it to regen if the player hasn’t taken damage in a couple seconds but if the player took damage, it will wait the regen time threshold until the cooldown has ended.
local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")
local regenTimeThreshold = 3 -- Time in seconds before regeneration starts after taking damage
local regenCooldown = 1 -- Time in seconds to keep regenerating after regen starts
local regenRate = 20 -- Amount of health regenerated per second
local regenTimeThresholdTime = tick()
local regenCurrentTime = tick()
local oldHealth = humanoid.Health
local RunService = game:GetService("RunService")
local regenTimeThresholdConnection
local regenConnection
local function setRegenTimeThresholdConnectionNil()
if regenTimeThresholdConnection then
regenTimeThresholdConnection:Disconnect()
regenTimeThresholdConnection = nil
end
end
local function setRegenConnectionNil()
if regenConnection then
regenConnection:Disconnect()
regenConnection = nil
end
end
local function regen()
regenConnection = RunService.Heartbeat:Connect(function(delta)
if tick() - regenCurrentTime >= regenCooldown then
regenCurrentTime = tick()
humanoid.Health += regenRate
end
end)
end
humanoid:GetPropertyChangedSignal("Health"):Connect(function()
if humanoid.Health < oldHealth then
setRegenTimeThresholdConnectionNil()
setRegenConnectionNil()
oldHealth = humanoid.Health
regenTimeThresholdTime = tick()
regenCurrentTime = tick()
regenTimeThresholdConnection = RunService.Heartbeat:Connect(function(delta)
if tick() - regenTimeThresholdTime >= regenTimeThreshold then
regenTimeThresholdTime = tick()
regen()
setRegenTimeThresholdConnectionNil()
end
end)
end
end)
humanoid.Died:Connect(function()
setRegenTimeThresholdConnectionNil()
setRegenConnectionNil()
end)