I'm trying to make a locked door that when you touch the locked door it plays a sound and enables a GUI saying that its locked, the problem is that when you press it, it tends to spam the sound and GUI.
script.Parent.Touched:Connect(function(hit) if hit.Parent:FindFirstChild("Humanoid")then game.ReplicatedStorage.LockedDoor:FireClient(game.Players:GetPlayerFromCharacter(hit.Parent)) end end)
^ The script that's in the door.
Howdy!
In the scripting world, we call this "debounce". Don't ask me why, the Code Gods just made it like that. The definition used by this site is:
Debounce is a term that is often associated with the act of adding a cool-down time to a function so it doesn't get called rapidly. This can be especially helpful when used in conjunction with the Touched event of parts. Oftentimes, this is accomplished by setting a variable to true at the beginning of a function, and setting it to false again at the end. Then, at the very beginning of the function, if the variable is already true, then you use the 'return' keyword, effectively ending the function.
Before your function, add a variable called "debounce" and set it to false. Then when the function is ran, set the debounce as true with a wait time of three seconds (or whatever you want). It'll look something like what I have below.
local Debounce = false script.Parent.Touched:Connect(function(hit) if hit.Parent:FindFirstChild("Humanoid") and not Debounce then Debounce = true game.ReplicatedStorage.LockedDoor:FireClient(game.Players:GetPlayerFromCharacter(hit.Parent)) wait(3) Debounce = false end end)
If this helped you out, consider accepting this answer for those sweet, sweet reputation points. If not, comment below and I (or someone else) will help you out.
I think you do this
local debounce = false script.Parent.Touched:Connect(function(hit) hit.Parent:FindFirstChild(“Humanoid”) then if debounce == false then debounce = true game.ReplicatedStorage.LockedDoor:FireClient(game.Players:GetPlayerFromCharacter(hit.Parent)) wait( insert amount of time before door makes sound plus GUI shows up again ) debounce = false end end end)
hopefully this was helpful and the correct answer