Cooldown on humanoid damage ignoring debounce

So I was working on a script of making a NPC hurt another player but ignores both the wait and the debounce on a loop

local canKill = true
script.Parent.Touched:Connect(function(hit)
	local h = hit.Parent:FindFirstChild("Humanoid")
	canKill = false
	if canKill == false then
		if h then
			if h.Parent.Name ~= "Zombie" then
				canKill = true
				h:TakeDamage(15)
				print("gave damage")
				wait(2)
				canKill = false
			end
		end
	end
end)


script.Parent.Parent.Humanoid.Died:Connect(function()
	script:Destroy()
end)

Every Comment appreciated!

try this

local canKill = true
script.Parent.Touched:Connect(function(hit)
	local h = hit.Parent:FindFirstChild("Humanoid")
		if h then
			if h.Parent.Name ~= "Zombie" then
	          if canKill == true then
                canKill = false
				h:TakeDamage(15)
				print("gave damage")
				wait(2)
				canKill = true
			end
		end
	end
end)


script.Parent.Parent.Humanoid.Died:Connect(function()
	script:Destroy()
end)

It doesn’t hurt the player at all now

You should create your variable before the .Touched event.

Something like that

local part = script.Parent
local debounce = false
part.Touched:Connect(function(hit)
	if debounce == false then
		debounce = true
		print("Part Touched")
		task.wait(2)
		debounce = false
	end
end)

But i’ve already done it though

you have to check & turn on & off the debounce after the checks i updated the code try it.

local canKill = true
script.Parent.Touched:Connect(function(hit)
	local h = hit.Parent:FindFirstChild("Humanoid")
	
	if canKill == true then
		if h then
			if h.Parent.Name ~= "Zombie" then
				canKill = false
				h:TakeDamage(15)
				print("gave damage")
				task.wait(2)
				canKill = true
			end
		end
	end
end)


script.Parent.Parent.Humanoid.Died:Connect(function()
	script:Destroy()
end)

Thank you ayoub50 and voxaim for the help! appreciated!

1 Like

Sorry I wasn’t clear enough. To make your debounce work you need first to create a variable

local debounce = false

And then to make a cooldown

part.Touched:Connect(function(hit)
	if debounce == false then -- Checks if debounce is false
		debounce = true -- sets to true
		print("Part Touched")
		task.wait(2) -- yield the script 
		debounce = false -- sets back to false
	end
end)

he already has a debounce variable which is called canKill

1 Like