Advanced regen system

I’m trying to make an advanced regen system which heals the player every .5 seconds, however if they get stunned, the timer resets and stops until they arent stunned anymore, after which it will then wait .5 seconds again.

However, the problem I’m having is that if they stunned and unstunned, sometimes they heal right away, but I want it to wait .5 seconds before healing them AFTER they arent stunned anymore.

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

local Values = Character.Values
local Rate = Values.RegenAmount.RegenRate.Value

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

while task.wait() do
	
	print("checking")
	
	if Values.Status.Stunned.Value ~= true and 
		Values.Status.Ragdolled.Value ~= true and 
		Values.Status.Grabbed.Value ~= true and 
		Humanoid.Health > 0
	then task.wait(Rate)
		
		print("final check")
		
		if Humanoid.Health < Humanoid.MaxHealth and
			Values.Status.Stunned.Value ~= true and 
			Values.Status.Ragdolled.Value ~= true and 
			Values.Status.Grabbed.Value ~= true and 
			Humanoid.Health > 0
		then
			Humanoid.Health += Values.RegenAmount.Value
			print("healed")
		end
	else
		continue
	end
end

In simpler terms:

When they are stunned, don’t regen.

After they are stunned, wait .5 seconds to regen.

3 Likes

Hello there!
while task.wait() do is a bad way to do a loop, I suggest changing it to while true do
and instead of else continue I suggest else task.wait().
I would also suggest adding a wait before regenerating.

So:

while true do
    if Values.Status.Stunned.Value then
        while Values.Status.Stunned.Value do -- // If the player is stunned, we wait until they are not stunned
            task.wait()
        end 
        task.wait(.5) -- // Wait the 0.5.
    else
        if Humanoid.Health > 0 and Humanoid.Health < Humanoid.MaxHealth then -- // Player is not stunned, we continue with regeneration
            task.wait(Rate)
            if not Values.Status.Stunned.Value then -- // Check stun status again in case player got stunned during the wait
                Humanoid.Health = math.min(Humanoid.Health + Values.RegenAmount.Value, Humanoid.MaxHealth)
                print("healed")
            end
        else
            task.wait() -- // To prevent exhaustion.
        end
    end
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.