Pathfinding optimization help please!

I have this code to make an NPC chase players, and it works but
lags very badly. Does anyone now how to help with this?

local PS = game:GetService("PathfindingService")
local RunService = game:GetService("RunService")

local players = game:GetService("Players")

local zombie = script.Parent
local humanoid = zombie:WaitForChild("Humanoid")

function chase(plrRoot)
	--print("chase function fired")
	
	local point = plrRoot.Position
	local path = PS:CreatePath({
		AgentRadius = 2,
		AgentHeight = 5,
		AgentCanJump = true,
		AgentJumpHeight = 10,
		AgentMaxSlope = 45,
	})
	
	
	local success, errorMessage = pcall(function()
		path:ComputeAsync(zombie.HumanoidRootPart.Position, point)
	end)
	
	
	if success and path.Status == Enum.PathStatus.Success then
		print("success")
		for _, waypoint in pairs(path:GetWaypoints()) do

			humanoid:MoveTo(waypoint.Position)

			if waypoint.Action == Enum.PathWaypointAction.Jump then
				humanoid.Jump = true
			end

			humanoid.MoveToFinished:Connect(function()
				print("moveto finished")
			end)
		end
	else
		warn("The path has unsuccessfully been created", errorMessage)
	end
end


RunService.Heartbeat:Connect(function()
	--print("hearbeat")
	for _, player in pairs(players:GetChildren()) do
		--print(player.Name)
		if not player.Character then
			break
		end
		
		local plrRoot = game.Workspace:FindFirstChild(player.Name).HumanoidRootPart
		if plrRoot then
			--print(player.Name, "plrRoot found")
		end
		
		--print((plrRoot.Position - zombie.PrimaryPart.Position).Magnitude)
		
		if plrRoot and (plrRoot.Position - zombie.PrimaryPart.Position).Magnitude <= 25 then
			--print("chasing", player.Name)
			chase(plrRoot)
		end
	end
end)

I’m desperate please someone anyone I just need to know how to optimize this :smiling_face_with_tear:

1 Like

Constantly creating new paths is pretty expensive so if your enviroment isn’t constantly changing, don’t make a new one constantly either. And only have one chase() running at a time, you call it every heartbeat.

Second, if the NPC has line of sight with the player, and there’s a negligible difference in height, don’t pathfind, just move directly to the target.

1 Like

Sorryy but how do I make it run less and stop chase() when it plays more than once? I’m new to pathfinding

you need to make the path cache and just have the NPC walk to each destination and use the provided events for when a path waypoint is completed, rather than running it on heartbeat, as thats very expensive.