How can i inprove this pathfinding script?

Today i started on a simple horror game project, and i had to figure out how to use path finding service for it. I looked over the devhub and i got a pretty basic grasp of it. I ended up making one of my test dummies follow the nearest player but its a little bit janky and not to my liking

Heres the code


local NPC = script.Parent
local Players = game.Players
local PFS = game:GetService("PathfindingService")

local function MoveToClosestPlayer()
	local npcHum = NPC.Humanoid
	local npcHRP = NPC.HumanoidRootPart
	local closestDistance = math.huge
	for i, player in pairs(Players:GetPlayers()) do
		print(player,"is player", i)
		local char = player.Character or player.CharacterAdded:Wait()
		if char then
			local HRP = char.HumanoidRootPart
		if HRP then
			local distance1 = (npcHRP.Position - HRP.Position).Magnitude
			if distance1 < closestDistance then
				print(distance1)
				local closestHRP = HRP
				print(closestHRP.Position)
						
				local destination = closestHRP.Position
				local path = PFS:CreatePath()
				path:ComputeAsync(npcHRP.Position, destination)
						
				local waypoints = path:GetWaypoints()
				for _, v in pairs(waypoints) do
					npcHum:MoveTo(v.Position)
						if v.Action == Enum.PathWaypointAction.Jump then
							npcHum.Jump = true
						end
					end
				end
			end
		end
	end
end

while task.wait() do
	MoveToClosestPlayer()
end

I believe i know where the issue is lying. The while wait is constantly running the function creating multiple paths and the dummy has to follow all of them making it look funny when it tries to follow the player. My questions are:

Is there any way to get around this without using a while loop?

Are there any improvements or things i should add to this script?

Feedback is much appreciated, thank you for your time :slightly_smiling_face:

Hey, use the SetNetworkOwner() on the humanoid Root part of the Npc to stop the lag issue like this:
npcHRP:SetNetworkOwner(nil) make sure to set it to nil. Now the Npc is assigned to the server side instead of it constantly switching from server to client causing it to lag.

For More information on this function: Network Ownership | Roblox Creator Documentation

1 Like

Have you also looked at other open source pathfinding solutions?

Like this module being spam proof, though there is a newer version. Perhaps you can also look there to see potential improvements in yours.

1 Like