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:
01 | print ( "Starting script" ) |
02 | game.Workspace:WaitForChild( "Humanoid" , 0.001 ) |
03 | print ( "found character" ) |
04 |
05 | local player = game.Players.LocalPlayer |
06 | local character = game.Players.LocalPlayer.Character |
07 | local TextLabel = script.Parent |
08 | local stop = game.Workspace.Stop |
09 | local start = game.Workspace.Start |
10 | local screengui = player.PlayerGui.ScreenGui |
11 |
12 | start.ClickDetector.MouseClick:Connect( function (click 1 ) |
13 | if click 1 then |
14 | print ( "clicked green button" ) |
15 |
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:
01 | local runLoop = true |
02 |
03 | for i = 1 , math.huge , 1 do |
04 | if runLoop = = false then |
05 | break |
06 | end |
07 | wait( 1 ) |
08 | end |
09 |
10 | stop.ClickDetector.MouseClick:Connect( function () |
11 | runLoop = false |
12 | 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:
01 | local canRun = true |
02 |
03 | start.ClickDetector.MouseClick:Connect( function () |
04 | if canRun = = true then |
05 | canRun = false |
06 | --run your stuff |
07 | end |
08 | end ) |
09 |
10 | stop.ClickDetector.MouseClick:Connect( function () |
11 | canRun = true |
12 | 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:
01 | print ( "Starting script" ) |
02 | game.Workspace:WaitForChild( "Humanoid" , 0.001 ) |
03 | print ( "found character" ) |
04 |
05 | local player = game.Players.LocalPlayer |
06 | local character = game.Players.LocalPlayer.Character |
07 | local TextLabel = script.Parent |
08 | local stop = game.Workspace.Stop |
09 | local start = game.Workspace.Start |
10 | local canRun = false |
11 | local runLoop = true |
12 |
13 | start.ClickDetector.MouseClick:Connect( function (click 1 ) |
14 | if canRun = = false then |
15 | canRun = true |