Debounce(Cooldown) not working in attack function

  1. What do you want to achieve? Keep it simple and clear!
    To make an attack function so that my Enemy AI attacks only one every 2 seconds if in proximity of the the player.

  2. What is the issue? Include screenshots / videos if possible!
    The code should work but the humanoid.takedamage lines seems to play every tik before the cooldown turns off. I’ve proven this by adding a print line and it can print up to 1000+ if the player is next to the AI for a second.

Attack Error

This is the code:

local function attack()
	local Cooldown = 3
	local Debounce = false
	if Debounce == false then
		Entity.Head.Touched:Connect(function(hit)
			if hit.Parent:FindFirstChild("Humanoid") then
				if hit.Parent.Humanoid.Health > 0 then
					Debounce = true
					Entity.Humanoid.WalkSpeed = Stopping
					Attack:Play()
					task.wait(0.5)
					hit.Parent.Humanoid:TakeDamage(10)
					print("You've been hit")

					task.wait(Cooldown)

					Attack:Stop()
					Entity.Humanoid.WalkSpeed = Walkspeed
					Attack.Stopped:Connect(function()
						Debounce = false
					end)
				end
			end
		end)
	end
end

The function is called within a heartbeat function, but I have ruled out that the heartbeat function isn’t the cause as it did this before I put it in a heartbeat function.

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I’ve tried to look at different selutions on the fourm and tried other code methods but none of them seem to work.

Does anyone know what the problem could be?

you need to disconnect the touch event after it’s triggered so it prevent multiple hits also just recreate the connection after the cooldown

local function attack()
    local Cooldown = 3
    local Debounce = false
    local connection

    connection = Entity.Head.Touched:Connect(function(hit)
        if not Debounce and hit.Parent:FindFirstChild("Humanoid") and hit.Parent.Humanoid.Health > 0 then
            Debounce = true
            connection:Disconnect()

            Entity.Humanoid.WalkSpeed = Stopping
            Attack:Play()
            task.wait(0.5)
            hit.Parent.Humanoid:TakeDamage(10)
            print("You've been hit")

            task.wait(Cooldown)

            Attack:Stop()
            Entity.Humanoid.WalkSpeed = Walkspeed
            Debounce = false

            attack()
        end
    end)
end
1 Like

Unfortunatly I looks like it hasn’t helped. Maybe it is my heartbeat function. But I am not really sure. I’ll send the whole code here:

local Players = game:GetService("Players")
local Pathfinding = game:GetService("PathfindingService")
local RunSerivce = game:GetService("RunService")
local Entity = script.Parent
local rig = Entity.Humanoid:FindFirstChild("Animator")
local Root = Entity:FindFirstChild("HumanoidRootPart")
local alignOrientation = Root:FindFirstChild("AlignOrientation")

-- Pathfinding AI
local Humanoid = Entity:WaitForChild("Humanoid")
Entity.PrimaryPart:SetNetworkOwner(nil)

local waypoints
local nextWaypointindx
local reachConnection
local blockedConnection

local Walkspeed = Entity:GetAttribute("Walkspeed")
local SprintSpeed = Entity:GetAttribute("SprintSpeed")
local Damage = Entity:GetAttribute("Damage")
local Stopping = Entity:GetAttribute("Stop")

local function getPath(destination)
	local path = Pathfinding:CreatePath({
		AgentHeight = 4,
		AgentRadius = 6,
		AgentCanClimb = true,
		AgentCanJump = true,

		Costs = {
			Water = math.huge
		}

	})

	path:ComputeAsync(Root.Position, destination.Position)

	return path
end

local function findTarget()
	local  nearestTarget
	local MaxDistance = 100

	for index, player in pairs(Players:GetPlayers()) do
		if player.Character then
			local target = player.Character
			local distance = (Root.Position - target.HumanoidRootPart.Position).Magnitude
			if distance < MaxDistance then
				nearestTarget = target
				MaxDistance = distance
			end
		end
	end
	return nearestTarget
end

local function attack()
	local Cooldown = 3
	local Debounce = false
	local connection
	
	connection = Entity.Head.Touched:Connect(function(hit)
		if not Debounce and hit.Parent:FindFirstChild("Humanoid") and hit.Parent.Humanoid.Health > 0 then
			 Debounce = true
            connection:Disconnect()

            Entity.Humanoid.WalkSpeed = Stopping
            Attack:Play()
            task.wait(0.5)
            hit.Parent.Humanoid:TakeDamage(10)
            print("You've been hit")

            task.wait(Cooldown)

            Attack:Stop()
            Entity.Humanoid.WalkSpeed = Walkspeed
			Debounce = false
			
			attack()
		end
	end)
end

local function Capture(target)
	local distance = (Root.Position - target.HumanoidRootPart.Position).Magnitude
	local counter = 0
	
	RunSerivce.Heartbeat:Connect(function(step)

		counter += step

		if counter >= 1 then

			counter = 0

			local NewPath = Pathfinding:CreatePath({
				["AgentHight"] = 4,
				["AgentRadius"] = 6,
				["AgentCanClimb"] = true,
				["AgentCanJump"] = true,

				Costs = {
					Water = math.huge
				}
			})

			NewPath:ComputeAsync(Root.Position, target.HumanoidRootPart.Position)

			if distance > 5 and target.Humanoid.Health > 0 then
				if NewPath.Status == Enum.PathStatus.Success then
					for index, target in pairs(NewPath:GetWaypoints()) do
						if not Walk.IsPlaying then
							Walk:Play()
						end
						Humanoid:MoveTo(target.Position)
						Humanoid.MoveToFinished:Wait()
						
					end
				else
					Humanoid:MoveTo(target.Position - (Root.CFrame.LookVector * 10))
				end
			else
				attack(target)
				wait(2)
			end	
		end
	end)
end

local function walkTo(destination)
	local path = getPath(destination)

	if path.Status == Enum.PathStatus.Success then
		for index, waypoint in pairs(path:GetWaypoints()) do
			local target = findTarget()

			if target and target.Humanoid.Health > 0 then
				Capture(target)
				break
			else
				Entity.Humanoid.WalkSpeed = Walkspeed
				Humanoid:MoveTo(waypoint.Position)
				Humanoid.MoveToFinished:Wait()
			end
		end
	else
		Humanoid:MoveTo(destination.Position - (Root.CFrame.LookVector * 10))
	end
end

local function Patrol()
	local waypoints = workspace.Waypoints:GetChildren()
	local ranWaypoint = math.random(1, #waypoints)
	walkTo(waypoints[ranWaypoint])

end


-- Excicute Sritp--

while wait(0.01) do
	Patrol()
end

can you try this i have modified it

local Players = game:GetService("Players")
local Pathfinding = game:GetService("PathfindingService")
local RunSerivce = game:GetService("RunService")
local Entity = script.Parent
local rig = Entity.Humanoid:FindFirstChild("Animator")
local Root = Entity:FindFirstChild("HumanoidRootPart")
local alignOrientation = Root:FindFirstChild("AlignOrientation")

local Humanoid = Entity:WaitForChild("Humanoid")
Entity.PrimaryPart:SetNetworkOwner(nil)

local waypoints
local nextWaypointindx
local reachConnection
local blockedConnection

local Walkspeed = Entity:GetAttribute("Walkspeed")
local SprintSpeed = Entity:GetAttribute("SprintSpeed")
local Damage = Entity:GetAttribute("Damage")
local Stopping = Entity:GetAttribute("Stop")

local function getPath(destination)
	local path = Pathfinding:CreatePath({
		AgentHeight = 4,
		AgentRadius = 6,
		AgentCanClimb = true,
		AgentCanJump = true,
		Costs = {
			Water = math.huge
		}
	})
	path:ComputeAsync(Root.Position, destination.Position)
	return path
end

local function findTarget()
	local  nearestTarget
	local MaxDistance = 100
	for index, player in pairs(Players:GetPlayers()) do
		if player.Character then
			local target = player.Character
			local distance = (Root.Position - target.HumanoidRootPart.Position).Magnitude
			if distance < MaxDistance then
				nearestTarget = target
				MaxDistance = distance
			end
		end
	end
	return nearestTarget
end

local Cooldown = 3
local Debounce = false

local function attack()
	local connection
	connection = Entity.Head.Touched:Connect(function(hit)
		if not Debounce and hit.Parent:FindFirstChild("Humanoid") and hit.Parent.Humanoid.Health > 0 then
			Debounce = true
			connection:Disconnect()
			Entity.Humanoid.WalkSpeed = Stopping
			Attack:Play()
			task.wait(0.5)
			hit.Parent.Humanoid:TakeDamage(10)
			print("You've been hit")
			task.spawn(function()
				task.wait(Cooldown)
				Debounce = false
			end)
			Attack:Stop()
			Entity.Humanoid.WalkSpeed = Walkspeed
		end
	end)
end

local function Capture(target)
	local distance = (Root.Position - target.HumanoidRootPart.Position).Magnitude
	local counter = 0
	RunSerivce.Heartbeat:Connect(function(step)
		counter += step
		if counter >= 1 then
			counter = 0
			local NewPath = Pathfinding:CreatePath({
				AgentHight = 4,
				AgentRadius = 6,
				AgentCanClimb = true,
				AgentCanJump = true,
				Costs = {
					Water = math.huge
				}
			})
			NewPath:ComputeAsync(Root.Position, target.HumanoidRootPart.Position)
			if distance > 5 and target.Humanoid.Health > 0 then
				if NewPath.Status == Enum.PathStatus.Success then
					for index, target in pairs(NewPath:GetWaypoints()) do
						if not Walk.IsPlaying then
							Walk:Play()
						end
						Humanoid:MoveTo(target.Position)
						Humanoid.MoveToFinished:Wait()
					end
				else
					Humanoid:MoveTo(target.Position - (Root.CFrame.LookVector * 10))
				end
			else
				attack()
			end	
		end
	end)
end

local function walkTo(destination)
	local path = getPath(destination)
	if path.Status == Enum.PathStatus.Success then
		for index, waypoint in pairs(path:GetWaypoints()) do
			local target = findTarget()
			if target and target.Humanoid.Health > 0 then
				Capture(target)
				break
			else
				Entity.Humanoid.WalkSpeed = Walkspeed
				Humanoid:MoveTo(waypoint.Position)
				Humanoid.MoveToFinished:Wait()
			end
		end
	else
		Humanoid:MoveTo(destination.Position - (Root.CFrame.LookVector * 10))
	end
end

local function Patrol()
	local waypoints = workspace.Waypoints:GetChildren()
	local ranWaypoint = math.random(1, #waypoints)
	walkTo(waypoints[ranWaypoint])
end

attack()

while true do
	Patrol()
	task.wait(0.01)
end

I’m not fully sure how you this but it worked like a dream!
Thank you so much it has fixed my damage dilemma.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.