Hello, I'm trying to make some code that will run a for loop to count up from 1 to infinity when you click a green button and stop the for loop when the red part is clicked and I'm not sure what to do. I'm asking if there's any way to stop or start a loop remotely? I'm also asked if there's a way to not run the code if I clicked the button more than once because if I click the button more than once, the code runs again and displays numbers all over.
Here's the code:
print("Starting script") game.Workspace:WaitForChild("Humanoid",0.001) print("found character") local player = game.Players.LocalPlayer local character = game.Players.LocalPlayer.Character local TextLabel = script.Parent local stop = game.Workspace.Stop local start = game.Workspace.Start local screengui = player.PlayerGui.ScreenGui start.ClickDetector.MouseClick:Connect(function(click1) if click1 then print("clicked green button") for i = 1,math.huge,1 do wait(1) TextLabel.Text = i end end end) stop.ClickDetector.MouseClick:Connect(function(click2) if click2 then print("clicked red button") -- what do I add here to make the for loop stop? end end)
We're gonna be using the 'break' function that stops/breaks loops.
You can have a variable determine whether or not the loop should continue running
Since you're using a for loop, you can just add an if statement for the variable, and if that variable is true/false, then break the loop
Example:
local runLoop = true for i=1,math.huge,1 do if runLoop == false then break end wait(1) end stop.ClickDetector.MouseClick:Connect(function() runLoop = false end)
As for stopping something from running multiple times, we're gonna use a debounce
Basically just a variable that determines if the thing is already running or not, if it is already running, then it won't run it again.
Example:
local canRun = true start.ClickDetector.MouseClick:Connect(function() if canRun == true then canRun = false --run your stuff end end) stop.ClickDetector.MouseClick:Connect(function() canRun = true end)
ez
I asked in the comments what I needed help with next so read that if you want.
Here was the code that I used with your help:
print("Starting script") game.Workspace:WaitForChild("Humanoid",0.001) print("found character") local player = game.Players.LocalPlayer local character = game.Players.LocalPlayer.Character local TextLabel = script.Parent local stop = game.Workspace.Stop local start = game.Workspace.Start local canRun = false local runLoop = true start.ClickDetector.MouseClick:Connect(function(click1) if canRun == false then canRun = true print("clicked green button") for i = 1,math.huge,1 do wait(1) TextLabel.Text = i if runLoop == false then break end end end end) stop.ClickDetector.MouseClick:Connect(function(click2) if click2 and runLoop == true then print("clicked red button") runLoop = false end end)