Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

how to fix While condtion firing even though variable is false?

I made customs stats for players. If the player gets damaged they cannot heal for 5 secs but the player still heals while printing "cannot Heal" which only happens if they recently took dmg.



if script.Parent.Parent.Name == "Backpack" then
	print("player found")

	local Hum = script.Parent.Parent.Parent.Character:FindFirstChild("Humanoid")


	local Speed = 30
	local Health = 145
	local Jump = 70
	local Regen = 3
	local RegenRate = 0.7 --seconds

	local healing = false
	local RecentDmg = false

	Hum.MaxHealth = Health
	Hum.Health = Health
	Hum.WalkSpeed = Speed
	Hum.JumpPower = Jump
	oldhp = Hum.Health 


	Hum.HealthChanged:Connect(function(hp)		
		if hp < oldhp then
			if RecentDmg == false then
				print("Cannot Heal")
				RecentDmg = true
				wait(5)
				RecentDmg = false
				print("can be healed")
				end
		end
	end)

	while true do
		local rate = wait(RegenRate)
		if RecentDmg == false then
			while Hum.Health < Hum.MaxHealth do
				if Hum.Health < Hum.MaxHealth/2 then	
					print("Regen Has been Doubled")
					Hum.Health += Regen*2
					wait(rate/2)

				else
					Hum.Health += Regen
					wait(rate)

				end

			end
		end
		end
end


1 answer

✓ Accepted answer

The problem is that you only check if RecentDmg == false then in your outer while loop, but then you have an inner while loop that will keep regenerating the player's health until its full regardless of RecentDmg's value. To fix, this remove the inner while loop (though not its contents!)

I also recommend removing the wait(rate/2) and wait(rate) commands - if you want to double the regeneration, just multiplying Regen*2 (as you currently have it) is sufficient.

I also expect that you can remove the first if statement (and its end of course), if script.Parent.Parent.Name == "Backpack" then, as I don't see why that would ever be false when this script starts up. If you suspect that it might be needed, reverse it:

if script.Parent.Parent.Name ~= "Backpack" then
	print("Ancestor isn't a backpack!")
	return
end
-- Rest of your code here

If the print statement occurs, you've confirmed that you need it (so then just remove the print statement), otherwise delete the whole if block since it's unnecessary.

3 comments

0

ook ty

0

Whenever I regen, "RecentDmg" is set to true so I have to wait 5 seconds each time I regen. how do I fix this?

0

Ah, there's another bug: you don't update oldhp after every Health change (at the end of the function). Also, is this a Script or a LocalScript? It needs to be a Script for the Health changes to actually take effect (otherwise you will only see the changes locally) - or use a RemoteEvent

This discussion is preserved as it was. New answers, comments, and votes are closed.