Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why is my for loop not using the wait function?

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

✓ Accepted answer

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!

2 comments

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.

0

Okay!

This discussion is preserved as it was. New answers, comments, and votes are closed.