Pathfinding script is not working whatsoever

What I want to make is a pathfinding npc that chases down players in range. However, when I tried to achieve this with the script below, it doesn’t work in a way that it is suppose to. Sure it walks and follow players but it just doesn’t use any pathfinding.

This is the code that I typed in, I’m so sorry for the long code :disappointed_relieved::

local PathfindingService = game:GetService("PathfindingService")
local maxDistance = 100
local myHuman = script.Parent:WaitForChild("Humanoid")
local hrp = script.Parent:WaitForChild("HumanoidRootPart")
local originalPosition = hrp.Position

local function target()
	local children = game.Workspace:GetChildren()
	for i, v in pairs(children) do
		if v:FindFirstChild("Humanoid") then
			if (v.HumanoidRootPart.Position - hrp.Position).Magnitude <= maxDistance then
				return (v.HumanoidRootPart.Position)
			end
		end
	end
end

local function paths(hrp)
	local playerTarget = target()
	if playerTarget ~= nil then
		local path = PathfindingService:CreatePath()
		path:ComputeAsync(hrp.Position, playerTarget)
		local waypoints = path:GetWaypoints()
		for i, waypoint in pairs(waypoints) do
			myHuman:MoveTo(waypoint.Position)
		end
	else
		myHuman:MoveTo(originalPosition)
	end
end

while wait(1) do
	paths(hrp)
end

My guess on what the cause of the problem is all the fast loops running simultaneously. A solution I tried to do to fix this problem is by adding a wait(1) . It worked a little but it wasn’t that smooth.

The code that I typed is possibly the most inefficient thing you ever seen and I am open for improvements. I am new to pathfinding and I hope I learn more about it.

Thanks in advance :slight_smile:

And yay! This is my first post!

Looks like you’re not waiting after the moveto is finished for each point, try humanoid.MoveToFinished:Wait()

That fixed the pathfinding issue but now the new issue is that the NPC is walking on outdated waypoints.

Then you need a system for dynamic pathfinding.

Where do I start for making dynamic pathfinding? Like some links that might help me out