Debounce wait time is not being respected?

I have a weird bug in my debounce (DB) in my weapon. Somehow the debounce time stops being respected after the first run or two. From what I tried debugging, it seems like the debounce is being delayed when it comes to be set to true. However that still does not justify the wait not to be respected…

This part of the script is in a module script and I have tried even checking that the Touched event is being fired once. Any thoughts on what’s happening?

Output:
image

Script:

--Playing the weapon sound, give damage and debounce
local DB = false -- [[DEBOUNCE BUG]]
function Hit(character, pickedWeapon, tag)
	local stats = character.Stats
	local target = stats.Target
	local weapon = character:FindFirstChild(tag)
	local sound = Instance.new("Sound", weapon)
	sound.SoundId = pickedWeapon.Sound
	--Touched event
	weapon.Touched:Connect(function(hit)
		print(DB) -- weird
		if target.Value then
			if target.Value.Zombie.Health.Value > 0 then
				if hit.Parent == target.Value then
					if not DB then
						DB = true --seems like this is not triggering
						sound:Play()
						handlers.zombies.Damage(character, target.Value)
					end
					wait(10) -- [DEBOUNCE SUBJECT TO CHANGE]
					DB = false
				end
			end
		end
	end)
end

I could be wrong, but every time hit.Parent == target.Value, you wait(10) and set DB to false. I think you should put it inside of the “if not DB then” statement.

if hit.Parent == target.Value then
if not DB then
DB = true --seems like this is not triggering
sound:Play()
handlers.zombies.Damage(character, target.Value)
wait(10) – [DEBOUNCE SUBJECT TO CHANGE]
DB = false
end
end
end

4 Likes

As the user above says, you’re waiting 10 seconds and setting the debounce variable to false every time Touched fires and the chain of conditions are met, not just when the desired debounced code is ran.

This means you have several instances of this function running asynchronously (because Touched can fire multiple times), all waiting 10 seconds and setting DB to false at different times. When the desired code actually runs and sets DB to true, it gets set back to false again by one of the other running instances of this function.

Try the following structure for your Touched handler.

local DB = false
weapon.Touched:Connect(function(hit)
	if not DB then
		if target.Value and target.Value.Zombie.Health.Value > 0 and hit.Parent == target.Value then
			DB = true
			
			sound:Play()
			handlers.zombies.Damage(character, target.Value)
			
			wait(10)
			DB = false
		end		
	end
end)
1 Like

Thanks, I did not realize this was happening :blush: