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

Why is my for loop not using the wait function?

Asked by 1 year ago

I tried to making a thing where when you click a button it makes your clicks leaderstats go up by 1. I can click fast, so i wanted a cooldown on 1 or 0.5 seconds. Here is my script:

for number = 1, 1 do
    script.Parent.MouseButton1Click:Connect(function()
        game.Players.LocalPlayer.leaderstats.Clicks.Value = game.Players.LocalPlayer.leaderstats.Clicks.Value + 1
    end)

    wait(1)

end

Can you tell me why there is no cooldown? Thanks!

1 answer

Log in to vote
1
Answered by 1 year ago
Edited 1 year ago

Solution

I recommend using a debounce instead. A debounce is like a toggle of whether you should do this or not. It is crucial if you want to set up a cooldown.

Problem

The reason why your script isn't working is because you're only connecting MouseButton1Click every 1 second. Connecting the event makes it so that the function you connected to the event will call whenever the event is fired.

Final Script

Normal Script inside the button:

local button = script.Parent
local player = button:FindFirstAncestorOfClass("Player")
repeat
    player = button:FindFirstAncestorOfClass("Player")
    task.wait()
until player ~= nil

local debounce = true
button.MouseButton1Click:Connect(function()
    if debounce then -- if debounce is true
        debounce = false

        local leaderstats = player:WaitForChild("leaderstats")
        local Clicks = leaderstats:WaitForChild("Clicks")
        Clicks.Value += 1

        task.delay(1, function() -- after 1 second, debounce will turn true
            debounce = true
        end)
    end
end)

Thanks @xInfinityBear for the suggestion to not use RemoteEvents!

1
Although this would work, I would not recommend using a Remote Event; especially when it is unnecessary. Exploiters could abuse this and give themselves as many clicks as they like. You only need to use a single server script; you can still get the player object from the server script, as the script would be a descendant of the player. xInfinityBear 1777 — 1y
0
Okay! T3_MasterGamer 2189 — 1y
Ad

Answer this question