Somtimes my tool won't damage? (Debounce issue?)

Sometimes my tool won’t damage the NPC, I’m pretty sure it’s because I didn’t properly debounce the script but I don’t know how to fix this. I tried changing the wait() in the touched event to .9 and that worked but instead of not registering damage sometimes, occasionally it would resister damage twice.


The second hit didn’t register

Code:

local tool = script.Parent
local safe = true
local debounce = false

local function OnTouch(NPC)
	if safe == false then
	if not debounce then
	debounce = true 
	local Enemy = NPC.Parent:FindFirstChild("NPC")
	if not Enemy then return end 
	Enemy:TakeDamage(1)	
	wait(1)
	debounce = false
	end
  end
end

tool.Handle.Touched:Connect(OnTouch)

script.Parent.Activated:Connect(function()
	safe = false
	wait(1)
	safe = true
end)

Try this:

local tool = script.Parent
local safe = true
local debounce = false

local function OnTouch(NPC)
	if safe == false then
	if not debounce then
	debounce = true 
	local Enemy = NPC.Parent:FindFirstChild("NPC")
	if not Enemy then return end 
	Enemy:TakeDamage(1)	
	wait(1)
	debounce = false
	end
  end
end

tool.Handle.Touched:Connect(OnTouch)

script.Parent.Activated:Connect(function()
        if safe == true then
	safe = false
	wait(1)
	safe = true
       end
end)

I tried this but sometimes it won’t damage at all now

Why do you need the Boolean variable “safe”? We already got debounce.

local tool = script.Parent
local debounce = false

local function OnTouch(NPC)
	if debounce == false then
	debounce = true 
	local Enemy = NPC.Parent:FindFirstChild("NPC")
	if not Enemy then return end 
	Enemy:TakeDamage(1)	
	wait(1)
	debounce = false
	end
  end

tool.Handle.Touched:Connect(OnTouch)


1 Like

Ah I see my mistake now. Thank you for the help!