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

How can I start and stop a loop using a button?

Asked by 4 years ago

I would like to make a button which when clicked would start a loop, but then if clicked again would cause the loop to stop. How could I do this?

2 answers

Log in to vote
0
Answered by
rabbi99 714 Moderation Voter
4 years ago

Use the while loop.

Make sure there is a clickdetector and that its parent is the button.

I made the script for you:

local button = script.Parent
local clickdetector = button.ClickDetector
local toggled = false


clickdetector.MouseClick:connect(function()
    if toggled == false then
        toggled = true
        while toggled == true do
            --your script here
        end
    end
    if toggled == true then
        toggled = false
    end
end)
Ad
Log in to vote
0
Answered by 4 years ago

Use break. break is used for any type of loop, for loops, repeat-until loops, or while loops. break is self-explanatory, it breaks the loop.

local clickDetector = workspace.Part.Clickdetector
while wait() do
    clickDetector.MouseClick:Connect(function()
        break
    end)
end

Answer this question