How to stop the Touched function [Description]

Developers, me need help.
Im touched with error: script.Parent.LeftFoot.Touched:Connect(myfunc)
myfunc takes damage -4.
When im go to NPC, then, NPC very quickly died.
I think that function starting very much times and makes very big damage
How to fix?

You can introduce a debounce variable.

Heres an article to explain it in detail: Debounce Article

You will need to add a wait()

If all the script does is damage, debounce alone wouldn’t be much help.

function myfunc()
if damage == false then
damage = true
script.Parent.Humanoid.Health = script.Parent.Humanoid.Health - 4 --I suppose this is how you did it...
wait(0.5)
damage = false
end
end
script.Parent.LeftFoot.Touched:Connect(myfunc)

Can you please show me myfunc?

Like @FactorOfTheThird said, you could use a Debounce. Alternatively, you could use the CanTouch property inside of a BasePart. CanTouch is a Boolean value that when false, will ignore all objects that touch the part.


Example of using Debounce

local debounce = false
local cooldownTime = 0.5 --Damage cooldown time
local part = workspace.Part --the part that deals the damage when touched
local damage = 4 -- the damage amount

local function onTouch(hit)
	if hit.Parent:FindFirstChildWhichIsA("Humanoid") then
		local humanoid = hit.Parent:FindFirstChildWhichIsA("Humanoid")
		if not debounce then
			debounce = true
			humanoid:TakeDamage(damage)
			wait(cooldownTime)
			debounce = false
		end
	end
end


part.Touched:Connect(onTouch)

Example of using CanTouch

local cooldownTime = 0.5 --Damage cooldown time
local part = workspace.Part --the part that deals the damage when touched
local damage = 4 -- the damage amount

local function onTouch(hit)
	if hit.Parent:FindFirstChildWhichIsA("Humanoid") then
		local humanoid = hit.Parent:FindFirstChildWhichIsA("Humanoid")
		part.CanTouch = false
		humanoid:TakeDamage(damage)
		wait(cooldownTime)
		part.CanTouch = true
	end
end


part.Touched:Connect(onTouch)

Hope this helps!

1 Like