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

How can I stop a while loop when a certain condition is met?

function hurt(hit)
		local fire = hit.Parent.Torso:FindFirstChild("Fire")
		local hp = hit.Parent:FindFirstChild("Humanoid")
			while fire do
		hp.Health = hp.Health -5
		wait(1)
		end
	end
lava.Touched:connect(hurt)

I'm trying to make it so that if fire is on the player the player takes damage and if it isn't the while loop stops. However, I dunno how to stop it.

I've tried this as well

function hurt(hit)
		local nofire = hit.Parent.Torso
		local fire = hit.Parent.Torso:FindFirstChild("Fire")
		local hp = hit.Parent:FindFirstChild("Humanoid")
			if fire then
				while true do
		hp.Health = hp.Health -5
		wait(1)
			if  nofire then
		hp.Health = hp.Health +0
				end
			end
		end
	end
lava.Touched:connect(hurt)

1 comment

0

Change the if statement to if fire==nil then break end which will stop the while loop

1 answer

✓ Accepted answer

The problem with this is that your variable fire is static. When you define it, it will always be true or false. You need to use the FindFirstChild function inside the definition of the while loop.

######Note: you can put the yield in the definition of the while loop as well :D

function hurt(hit)
	local hp = hit.Parent:FindFirstChild("Humanoid")
	while hit.Parent.Torso:FindFirstChild("Fire") and wait(1) do
		hp.Health = hp.Health - 5
	end
end

lava.Touched:Connect(hurt) --'connect is deprecated - Use Connect.

Assuming there is a Fire Instance inside the Torso, the script will continue to damage the player every second.

1 comment

0

Thank you!!

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