How To Make Damage Script With Delay

So. I’m trying to make a part that when player touched, the player will deal damage but I want it to have delay so that they could still walk on that part and not completely killing them. Script that I tried to use:

function onTouched(hit)
	local human = hit.Parent:findFirstChild("Humanoid")
	if (human ~= nil) then
		while true do
			wait(5)
			human.Health = human.Health - math.random(20,30)
		end
	end
end
script.Parent.Touched:connect(onTouched)

The simple way to deal with it is to have a “debounce”. So using your original script:

local debounce = false
function onTouched(hit)
	if debounce  == true then return end
	local human = hit.Parent:findFirstChild("Humanoid")
	if (human ~= nil) then
		human.Health = human.Health - math.random(20,30)
		debounce = true
		wait(3) -- Cooldown period for debounce
		debounce  = false
	end
end
script.Parent.Touched:connect(onTouched)
3 Likes