Pathfinding error

I’m currently trying to make an NPC follow a player with PathfindingService. Initially, it worked fine, but after a while, a bug occurred. Here’s a demonstratory video:

And here’s my code:

local path = PathfindingService:CreatePath({AgentCanJump = true, WaypointSpacing = 2})
		local targetWaypointIndex = 2
		while true do
			local shortestDistance = 500
			local closestTarget
			for i, child2 in pairs(game.Players:GetChildren()) do
				if child:FindFirstChild("HumanoidRootPart") then
					if child2.Character and child2.Character:FindFirstChild("HumanoidRootPart") and (child2.Character.HumanoidRootPart.Position - child.HumanoidRootPart.Position).magnitude < shortestDistance then
						shortestDistance = (child2.Character.HumanoidRootPart.Position - child.HumanoidRootPart.Position).magnitude
						closestTarget = child2.Character			
					end
				else
					return
				end
			end
			if closestTarget then
				local success, errorMessage = pcall(function()
					if closestTarget then
						path:ComputeAsync(child.HumanoidRootPart.Position, closestTarget.HumanoidRootPart.Position)
					end
				end)
				local waypoints = path:GetWaypoints()
				print(waypoints[2] and waypoints[2].Action, waypoints[3] and waypoints[3].Action)
				if waypoints[targetWaypointIndex] then
					local part = Instance.new("Part", workspace)
					part.Anchored = true
					part.CanCollide = false
					part.Size = Vector3.new(1, 1, 1)
					part.Position = waypoints[2].Position
					part.Material = Enum.Material.Neon
					if waypoints[targetWaypointIndex].Action == Enum.PathWaypointAction.Jump then
						child.Humanoid.Jump = true
						child.Humanoid:MoveTo(waypoints[targetWaypointIndex].Position)
						targetWaypointIndex = 3
					else
						targetWaypointIndex = 2
						child.Humanoid:MoveTo(waypoints[targetWaypointIndex].Position)
						child.Humanoid.MoveToFinished:Wait()
					end
					if waypoints[targetWaypointIndex + 1] then
						local part2 = Instance.new("Part", workspace)
						part2.Anchored = true
						part2.CanCollide = false
						part2.Size = Vector3.new(1, 1, 1)
						part2.Position = waypoints[2].Position
						part2.BrickColor = BrickColor.new("Really red")
						if waypoints[3].Action == Enum.PathWaypointAction.Jump then
							child.Humanoid.Jump = true
							child.Humanoid:MoveTo(waypoints[targetWaypointIndex + 1].Position)
							targetWaypointIndex = 3
						else
							targetWaypointIndex = 2
							child.Humanoid:MoveTo(waypoints[targetWaypointIndex + 1].Position) 
							child.Humanoid.MoveToFinished:Wait()
						end
					end
				else
					wait()
				end
				waypoints = nil
			else
				wait()
			end	
			local shortestDistance, closestTarget = nil, nil
		end

Use a file converter (eg; cloudconvert.com) so that people can view the video without having to manually download it.

1 Like