Problem with raising number value with button

Hello! I have a problem with a script and I need help on how to solve it

So, I am trying to make a number value rise by pressing a button, I have tried one solution

function onClick()

while true do

game.Workspace.Temp.Value = game.Workspace.Temp.Value+2

end

wait(0.1)

end

but everytime I use it, It will do nothing, and then when I put script.Parent.MouseClick:connect(onClick) at the bottom of the script, It will freeze my game and put very high numbers on it when I want it to be smooth

It’s a simple typo buddy.
You put the wait outside the while true loop.

Btw what you did would keep automatically rising the value.

1 Like

You don’t have a wait inside of the while loop, so it will increase the value 100s of times a second, causing immense lag. Try this:

function onClick()

        while wait(0.1) do

            game.Workspace.Temp.Value = game.Workspace.Temp.Value+2

      end
 
end

script.Parent.MouseClick:connect(onClick)

Also, what is currently going to happen is every time they click the button, it will make a new connection. That means that if they pressed it 10 times, you would have 10 While loops going on forever. Is that what you want?

2 Likes

It works! Thank you so much for your help :slight_smile:

1 Like

Its kind of not, because I need help now when I press the button again, It stops rising, Is there a solution to that?

I would love to help you, can you explain further?

Do you want the number value to increase continuously when you click the button? If then what do you want to happen when the button is clicked again.

You can also do:

game.Workspace.Temp.Value += 2

There are more efficient ways to do this using coroutines, but this is a simple way that is easier to understand.

local increasing = false

script.Parent.MouseClick:Connect(function()
       increasing = not increasing --set "increasing" to the opposite of what it is (true to false) or (false to true)
end

while wait(0.5) do
      if increasing == true then --check if we want to increase it
             game.Workspace.Temp.Value = game.Workspace.Temp.Value+2
     end
end