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

Help with functions?

Asked by
iLegitus 130
9 years ago

So,If a function is connected once pressed a key,Wich i have already done,Is there a way you can time it? Like anti-spammable? Youve got to wait like 3 seconds for example? Any tips or answers please?

2 answers

Log in to vote
1
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
9 years ago

Yes, you can. It's called a debounce. A debounce is basically a variable that is usually set to false. When a player does something, you set it to true. However, you use a if statement so that the code will only execute when the variable equal false. Therefore, you can use this to prevent your code from running multiple times in a given time frame.

This is most commonly used in Touched events, so I'll make that my example.

local debounce = false
script.Parent.Touched:connect(function(hit)
    if debounce == false then --If debounce is false
        debounce = true --Set it to true, so that the code cannot run again until it equals false.
        print("You touched me!")
        wait(3) --After 3 seconds
        debounce = false --Set it to false so that the code can run again.
    end
end)

Ad
Log in to vote
1
Answered by
Discern 1007 Moderation Voter
9 years ago

Use tick() to measure the time between your press and the last time the function ran.

NOTE: Not Tested. May not work.

waittime = 3 --How much time you want between each press.
requiredkey = "r" --The key you need to press for the function to run
local mouse = game.Players.LocalPlayer:GetMouse() --Get the mouse.

lastran = 0 --For use later

local function onKeyDown(key) --Key is what key the player pressed
    lastpressed = tick() --Last time someone pressed the button
    if string.lower(key) == string.lower(requiredkey) and lastpressed - lastran >= waittime then --Checks if player pressed the right button, and checks if there were 3 seconds between the last time the player pressed the button and the last time the function ran
        --Do what you want the button to do here
        lastran = tick() --Sets a variable for the last time the function ran
    end --End the if statement
end --End the function

mouse.KeyDown:connect(onKeyDown) --Connect the function to the mouse
0
Or do that... I think a debounce would be easier though. Perci1 4988 — 9y
0
I personally think ticks are more efficient, since there is no waits. If you have a wait, the script is still running in the background, and it may cause lag if you have a big game with multiple things running. Your post below would very well work, but I prefer ticks. Discern 1007 — 9y

Answer this question