Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to make it so enemies have delay between attacks?

I have this code:

function onTouched(part)

local h = part.Parent:findFirstChild("Humanoid")

if h~=nil then

h.Health = h.Health -25

script.Parent.Impact:Play()

end

end

script.Parent.Touched:connect(onTouched)

how would i make it so that when it touches the player, it has a delay between attacks? I tried putting a wait(5) before the first end, but that didn't work.

2 answers

✓ Accepted answer

Most people like to use a debounce, like so:


local debounce = false -- Basically a debounce for your delay.
local delay = 5 -- seconds before they can attack again.

function onTouched(otherPart)
	local h = otherPart.Parent:FindFirstChild('Humanoid')
	if h then
	debounce = true
	h.Health = h.Health - 25
	script.Parent.Impact:Play()
	wait(5)
	debounce = false
	end
end

script.Parent.Touched:Connect(onTouched)

2 comments

0

Sorry forgot one important thing, where it says 'if h then', replace with 'if h and debounce == false' then. Apologises.

0

i would recommend using if not debounce then , since its more clean

Use debounce, because if you put wait(5) in the onTouched event it will just wait inside the function, it won't wait for all touched events

local debounce = false
function onTouched(part)
if not debounce then -- check if debounce is false
local h = part.Parent:findFirstChild("Humanoid")

if h~=nil then
debounce = true -- there is a character so we enable debounce to prevent it from loading again
h.Health = h.Health -25

script.Parent.Impact:Play()
wait(5) -- we wait 5 seconds

debounce = false -- we disable debounce so this can run again
end
end
end

script.Parent.Touched:connect(onTouched)

how would i make it so that when it touches th

This discussion is preserved as it was. New answers, comments, and votes are closed.