A quick but useful tip about debounces

Let’s say that we’re scripting a part that deals damage to the player’s character. Below, you will find an example of how the script is usually written:

local debounce = false

workspace.Part.Touched:Connect(function(otherPart)
   local humanoid = otherPart.Parent:FindFirstChild("Humanoid")

   if humanoid and not debounce then
      debounce = true
      humanoid:TakeDamage(20)
      task.wait(1)
      debounce = false
   end
end)

While the example does work in preventing the part from damaging the character too quickly, it’s important to remember what’s actually happening behind the scenes whenever it runs with the debounce active:

Touched event fires → Attempts to find a Humanoid inside the otherPart’s parent, using the FindFirstChild function → If statement returns true for the Humanoid, and false for the debounce. The function concludes

While I must admit that the example I provided isn’t particularly demanding to run, imagine if a lot of heavy code is executed before the condition of the debounce is checked. You’d be essentially forcing the server or client to do a lot of work, and then throwing away the result. That is why I always recommend checking for the debounce first thing inside the function, like so:

local debounce = false

workspace.Part.Touched:Connect(function(otherPart)
   if not debounce then
      local humanoid = otherPart.Parent:FindFirstChild("Humanoid")

      if humanoid then
         debounce = true
         humanoid:TakeDamage(20)
         task.wait(1)
         debounce = false
      end
   end
end)

As this will be the result:

Touched event fires → If statement returns false for the debounce. The function concludes

In the end, both examples end up with the exact same result, but the second example is the one I recommend and personally use. Thank you for reading my tutorial, and as a final tip: I also recommend taking frequent pauses when scripting, and to try to imagine how the script you are currently writing will be executed, as it helps to find useful tricks like this one :slight_smile:

3 Likes

Hey thanks for the tip lad, keep up the good work :slight_smile:

2 Likes

could also put a guard clause and save some indentation… easier to read

workspace.Part.Touched:Connect(function(otherPart)
  if debounce then return end
  
  -- do stuff
end)
1 Like