Npc lags game when it attacks

i cant seem to figure out why the npc lags the game whenever it attacks :pensive:


local humanoid = Zombie.Zombie

local animator = humanoid:WaitForChild("Animator",5)

local attackanim = animator:LoadAnimation(script.Attack)

local sounds = script.Parent.Head

local function attack(plr)
	Zombie.Zombie:MoveTo(plr.HumanoidRootPart.Position)
	script.Parent.HumanoidRootPart.Touched:Connect(function(hit)
		if hit.Parent:FindFirstChild("Humanoid") and debounce == false then
			if hit.Parent.Humanoid.Health > 0 then
				debounce = true
				Zombie.Zombie.WalkSpeed = 0.001
				attackanim:Play()
				sounds.S_Attack:Play()
				hit.Parent.Humanoid:TakeDamage(20)
				wait(0.3)
				Zombie.Zombie.WalkSpeed = 20
				wait(1)
				debounce = false
			end
		end
	end)
end

local canDie = true

local reward = 50

while wait() do
	path:ComputeAsync(Zombie.HumanoidRootPart.Position, Vector3.new(math.random(-100,200), 0, math.random(-100,200)))
	waypoints = path:GetWaypoints()
	for i, waypoint in pairs(waypoints) do
		local targetplr = findTarget()
		if targetplr then
			attack(targetplr)
		else
			Zombie.Zombie:MoveTo(waypoint.Position)
			Zombie.Zombie.MoveToFinished:Wait()
		end
		if Zombie.Zombie.Health <= 0 then
			local tag = script.Parent.Zombie:FindFirstChild("creator")
			local msg = script.TextLabel
			
			local killed = true
			local txt = [[<font color="rgb(170, 72, 72)">Killed: </font>]]
			
			msg.Visible = false
			if tag and canDie then
				canDie = false
				local player = tag.Value
				local leader = game.ServerStorage.PlayerCash:FindFirstChild(player.Name)
				print(leader)
				leader.Value = leader.Value + reward
			end
			msg.Visible = true
			if killed then
				msg.Text = txt..Zombie.Zombie.Parent.Name.." +$"..reward
			end
			msg.Parent = tag.Value:FindFirstChild("PlayerGui").KillNotification.Frame
			wait(5)
			script:Destroy()
		end
	end
end

Try a quick test, remove the part where it makes you take damage. If you still lag it might not be the attacking part. However, to make sure, remove the attacking part temporarily and check. If it’s still laggy after touching the npc, it may be due to something with the collisions.

ok, i have tested and the lag is gone after removing the attacking part so how can i go about fixing the attack part?

The problem might come from the fact that every time that you call the attack function you also connect another new function to the Touched event. These connected functions cumulate and end up causing lag.

In order to fix it, you should connect the Touched event only once or disconnect the functions from the event once finished or after some time.

1 Like