Creating debounce for touch functions

Hi all,

I’m writing a script for subway track-side signals. Each signal has 1 script which senses the special part touching it then calls a module script function, which actually does things. My current method is to use a special part that triggers a function in a module which does things like update the signal aspect and the control board. I’m trying to write a 5 second debounce after a function is fired (see the script below), as, in its current state, the function is called a lot. This, as you can imagine, puts a lot of stress on the server.

I looked into using :Disconnect() and :Connect() (with a wait(x) in between) but I’m not sure how to make that possible. I’d also like to keep as much code as possible in the module script, as there are going to be around 100 signals in the game. What would you guys do?

Signal script:

local SignalModule = require(workspace.SignalModule)
local Block = script.Parent
local ExitSensor = script.Parent.ExitSensor
local signal = script:FindFirstAncestorWhichIsA("Model").Name
local entering
local exiting

entering = Block.Touched:Connect(function(s)
  if s.Name == "TrippingBrickA" or "TrippingBrickB" then
    SignalModule.BlockEnter(Block.Name,s)
  end
end)

exiting = ExitSensor.Touched:Connect(function(s)
  if s.Name == "TrippingBrickA" or "TrippingBrickB" then
    SignalModule.BlockExit(Block.Name,signal)
  end
end)

Module script:
local signals = {}

function BlockEnter(block,s)
local target = s.Parent:FindFirstChild(block)
if target ~= nil then
target.Transparency = 1
target.CanCollide = false
signals[block] = true
print(block…" entered")
end
end

function BlockExit(block,signal)
local target = workspace[signal]:FindFirstChild(block)
if target ~= nil then
target.Transparency = 0
target.CanCollide = true
signals[block] = false
print(block…" exited")
end
end

while true do do
for i,v in pairs(signals) do
if v == true then
print(i…" present")
else
print(i…" not present")
end
end
wait(5)
end
end

lets use your “entering for example”

you can create a simple debounce like this (idk if this is what u want)

local Debounce = false

entering = Block.Touched:Connect(function(s)
  if not Debounce then
    if s.Name == "TrippingBrickA" or "TrippingBrickB" then
      Debounce = true
      SignalModule.BlockEnter(Block.Name,s)
      wait(1)
      Debounce = false
    end
  end
end)

probably not the best way, but it should work

oh yea and i’ve heard you should use task.wait instead of wait but idk what the difference is so i just used wait here

1 Like