Delayed health regeneration

Hello,

I am trying to replace the health script of all players with a custom script that waits until a player has not taken damage for 5 seconds and then rapidly heals them. I have tried adjusting the settings of the generic health script and adding an if statement to see if the player’s health continues to drop, but all that happens is that it waits 5 seconds and regens health rapidly regardless of damage taken.

Here is the last thing I tried:

-- Rapidly regen health over time if damage hasn't been taken for 5 seconds

local REGEN_RATE = 1/10 -- Regenerate this fraction of MaxHealth per second.
local REGEN_STEP = 5 -- Wait this long between each regeneration step.

--------------------------------------------------------------------------------

local Character = script.Parent
local Humanoid = Character:WaitForChild'Humanoid'

--------------------------------------------------------------------------------

while true do
	
	while Humanoid.Health < Humanoid.MaxHealth do
		local h1 = Humanoid.Health
		if Humanoid.Health < h1 then
			break
		else
			local dt = wait(REGEN_STEP)
			local dh = dt*REGEN_RATE*Humanoid.MaxHealth
			Humanoid.Health = math.min(Humanoid.Health + dh, Humanoid.MaxHealth)
		end
	
	end
	Humanoid.HealthChanged:Wait()
end

I have tested everything a ton of times, so I know my script to replace the health script is working properly.

Thanks for reading.
-Danny

6 Likes

From what it looks like, your current code does not account for any damage taken during the 5 second wait. Perhaps add a section into your code that will check to see if the player’s health has dropped before regeneration begins or during regeneration, and if it has dropped before/during regeneration, you can set it to wait 5 seconds before continuing to rapidly heal the player.

5 Likes

You need a cool down timer to act as a debounce,that sets to 5 when you take damaged, and decreases by (dt) every loop.

Humanoid.HealthChanged:Connect(function(dif) 
   If dif < 0 then -- you'll have to test this, I wrote this quick on mobile. 
      debounce = 5
   end
end


local debounce = 0
while true do
  local dt = wait(1/5)
  debounce = debounce - dt
  
   If debounce <= 0 and Humanoid.Health < Humanoid.MaxHealth then
      Humanoid.Health = Humanoid.MaxHealth + 50*dt
    end
end

10 Likes

I see.

I needed the HealthChanged function to detect the loss in health.

Thanks!

3 Likes