Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 7 years ago
Edited 7 years ago
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)
0
Change the if statement to if fire==nil then break end which will stop the while loop coolallball 0 — 7y

1 answer

Log in to vote
0
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
7 years ago
Edited 7 years ago

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.

0
Thank you!! NickLeBuilder 13 — 7y
Ad

Answer this question