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

How do I use debounce in userinputservice?

I've run in to an issue with UserInputService:

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local OpenDoor = game:GetService("ReplicatedStorage").OpenDoor
local UIS = game:GetService("UserInputService")
UIS.InputBegan:connect(function(input)
    if input.KeyCode == Enum.KeyCode.E then
        if mouse.Target then
            OpenDoor:FireServer(mouse.Target)
        end
    end
end)

This works fine^ But when I try and put a debounce (so players dont spam it) it breaks, this is how I did the debounce:

local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
local OpenDoor = game:GetService("ReplicatedStorage").OpenDoor
local UIS = game:GetService("UserInputService")
debounce = true
UIS.InputBegan:connect(function(input)
    if debounce == true then
        debounce = false
        if input.KeyCode == Enum.KeyCode.E then
        if mouse.Target then
            OpenDoor:FireServer(mouse.Target)
            debounce = true
        end
    end
    end
    
end)

Theres no errors or anything, it just doesn't work.

1 answer

✓ Accepted answer

The debounce above won’t prevent spamming, as there is no yield provided, this is mainly the way I use debounces, I hope this works for you:

local UserInputService = game:GetService("UserInputService")

local Player = game:GetService("Players").LocalPlayer
local Cursor = Player:GetMouse()

local Debounce, Yield = false, .5 --// five millisecond wait

UserInputService.InputBegan:Connect(function(Input, GameProcessed)
    if (Debounce or GameProcessed) then return end; Debounce = true
    --// Code
    wait(Yield)
    Debounce = false
end)

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