NPC's debounce doesnt work properly

I made aggressive Npc that deals damage to nearest player in distance, but damaging debounce doesnt work properly

NPC deal damage TWICE before his debounce set to true, I think thats cause of heartbeat function but i dont know how to fix it

Script:

local char = script.Parent
local hum = char:FindFirstChildOfClass("Humanoid")
local animator = hum:FindFirstChildOfClass("Animator")
local hrp = char.PrimaryPart

local detectPart = hrp
local maxDistance = 30

local idleAnim = animator:LoadAnimation(script.idle)
local walkAnim = animator:LoadAnimation(script.walk)
idleAnim:Play()

local function hasProperty(object, prop)
	local t = object[prop]
end

for i,v in pairs(script.Parent:GetDescendants()) do
	local success = pcall(function() hasProperty(v, "CollisionGroup") end)

	if success then
		v.CollisionGroup = "NPC"
	end
	if v:IsA("Part") or v:IsA("BasePart") or v:IsA("MeshPart") then
		v:SetNetworkOwner(nil)
	end
end

local debounce = false

game:GetService("RunService").Heartbeat:Connect(function()
	local nearestPlayer, nearestDistance, distance
	for _, player in pairs(game.Players:GetPlayers()) do
		local character = player.Character
		distance = player:DistanceFromCharacter(detectPart.Position)
		if not character or 
			distance > maxDistance or
			(nearestDistance and distance >= nearestDistance)
		then
			continue
		end
		nearestDistance = distance
		nearestPlayer = player
	end
	if nearestPlayer ~= nil then
		hum:MoveTo(nearestPlayer.Character.PrimaryPart.Position)
		if idleAnim.IsPlaying then
			idleAnim:Stop()
			walkAnim:Play()
			hum.WalkSpeed = 10
		end
		if distance < 2 and debounce == false then
			spawn(function()
				debounce = true                       <--------------
				print("5 taken")
				nearestPlayer.Character.Humanoid:TakeDamage(5)
				task.wait(1)
				debounce = false
			end)
		end
	else
		if walkAnim.IsPlaying then
			walkAnim:Stop()
			idleAnim:Play()
			hum:MoveTo(hrp.Position)
		end
	end
end)

From my testing, the spawn call is delaying setting the debounce to true long enough for the Heartbeat event to fire again, hence why it is running twice. You can just remove spawn and everything will work as intended.

Edit:
The docs for spawn say this:

Heartbeat appears to run every <20 ms, so it is running again before spawn updates the debounce.

Thank you!
After I put debounce = true outside of spawn function it work as i expect.

1 Like

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