Pathfinding starting the second time, but not finishing

I am trying to make an AI wander around to different specific points, but the second time it moves it will only move to the first points.

For instance, when I run the game in studio, the bot will move to its first points successfully. Afterwards, it will just turn once and not move at all after that.

(No errors are shown when running the script)

Here is the part of the script that is failing:

local function followPath(destination)
	
	local success, errormessage = pcall(function()
		path:ComputeAsync(Character.PrimaryPart.Position, destination)
	end)
	
	if success and path.Status == Enum.PathStatus.Success then
		waypoints = path:GetWaypoints()
		
		blockedConnection = path.Blocked:Connect(function(blockedWaypointIndex)
			if blockedWaypointIndex >= nextWaypointIndex then
				blockedConnection:Disconnect()
				followPath(destination)
			end
		end)

		if not reachedConnection then
			reachedConnection = humanoid.MoveToFinished:Connect(function(reached)
				if reached and nextWaypointIndex < #waypoints then
					nextWaypointIndex += 1
					humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
				else
					reachedConnection:Disconnect()
					blockedConnection:Disconnect()
				end
			end)
		end
		
		nextWaypointIndex = 2
		humanoid:MoveTo(waypoints[nextWaypointIndex].Position)
	end
end
1 Like

You are not looping through all of the returned waypoints. Once you have done GetWaypoints(), you then need to loop through each in turn:

waypoints = path:GetWaypoints()
for _, waypoint in ipairs(waypoints) do
	-- Your code block in here
end
1 Like

Would this still work if I have another part of the script that is constantly calling this function when a player is in range?

spawn(function()
	while wait() do
		local target = findTarget()
		if target then
			followPath(target.HumanoidRootPart.Position)
		end
	end
end)