I am making a script so when a player clicks a particular part it increases variable 'progress' whilst they are within range of the part. The first script is here:
01 | local working = false |
02 | local toolbox = script.Parent.Parent.Parent.Workspace.gen 1. toolbox.detector |
03 | local clickDetector = toolbox:WaitForChild( "ClickDetector" ) |
04 | clickDetector.MouseClick:Connect( function (Player) |
05 | while wait( 1 ) do |
06 | local Mag = (script.Parent.toolbox.walkto.Position-Player.Character.HumanoidRootPart.Position).magnitude |
07 | if Mag > = script.Parent.Range.Value then |
08 | working = false |
09 | print ( "working = false" ) |
10 | end |
11 | if Mag < = script.Parent.Range.Value then |
12 | working = true |
13 | game.Workspace.gen 1. working:Fire() |
14 | print ( "working = true" ) |
15 | end |
16 | end |
17 | end ) |
The script that increments the value when the event is fired is here:
1 | local progress = 0 |
2 | game.Workspace.gen 1. working.Event:Connect( function () |
3 | wait( 1 ) |
4 | progress = progress + 1 |
5 | print (progress) |
6 | end ) |
My problem is that the player can just click click detector infinitley spamming the event to update progress by one, how can I debounce this?
This should work:
01 | local working, debounce = false , true |
02 | local toolbox = script.Parent.Parent.Parent.Workspace.gen 1. toolbox.detector |
03 | local clickDetector = toolbox:WaitForChild( "ClickDetector" ) |
04 | local waitTime = 1 |
05 | clickDetector.MouseClick:Connect( function (Player) |
06 | while wait() do |
07 | local Mag = (script.Parent.toolbox.walkto.Position-Player.Character.HumanoidRootPart.Position).magnitude |
08 | if Mag > = script.Parent.Range.Value then |
09 | working = false |
10 | print ( "working = false" ) |
11 | end |
12 | if Mag < = script.Parent.Range.Value and debounce then |
13 | debounce = false |
14 | working = true |
15 | game.Workspace.gen 1. working:Fire() |
second script:
1 | local progress = 0 |
2 | game.Workspace.gen 1. working.Event:Connect( function () |
3 | progress = progress + 1 |
4 | print (progress) |
5 | --adding a wait in this code won't do any thing besides delay the code. |
6 | end ) |
(Sorry that my first awnser wasn't what you wanted. I misunderstuud your question.)