Hello,
01 | local pathFindingService = game:GetService( "PathfindingService" ); |
02 | local path = pathFindingService:CreatePath(); |
03 | local NPC = script.Parent; |
04 | local NPC_Humanoid = NPC.Humanoid; |
07 | local currentWaypointIndex = 1 ; |
09 | local function findNearestPlayer(position) |
10 | local lowest = math.huge ; |
13 | for _, v in pairs (game.Players:GetPlayers()) do |
16 | local distance = v:DistanceFromCharacter(position); |
17 | if distance < = lowest then |
20 | print (nearestPlayer.Name.. " is closest player at a distance of :" .. distance ); |
28 | local function followPath(player) |
29 | path:ComputeAsync(NPC.HumanoidRootPart.Position, player.Character.HumanoidRootPart.Position); |
32 | if path.Status = = Enum.PathStatus.Success then |
33 | waypoints = path:GetWaypoints(); |
35 | print (currentWaypointIndex) |
36 | NPC_Humanoid:MoveTo(waypoints [ currentWaypointIndex ] .Position); |
38 | NPC_Humanoid:MoveTo(NPC.HumanoidRootPart.Position); |
43 | local function onWaypointReached(reached) |
44 | if reached and currentWaypointIndex < #waypoints then |
45 | currentWaypointIndex = currentWaypointIndex + 1 ; |
46 | NPC_Humanoid:MoveTo(waypoints [ currentWaypointIndex ] .Position); |
50 | local function onPathBlocked(blockedWaypoint) |
52 | if blockedWaypoint > currentWaypointIndex then |
53 | local nearestPlayer = findNearestPlayer(NPC.HumanoidRootPart.Position); |
54 | followPath(nearestPlayer); |
61 | local nearestPlayer = findNearestPlayer(NPC.HumanoidRootPart.Position); |
63 | followPath(nearestPlayer); |
68 | path.Blocked:Connect(onPathBlocked) |
70 | NPC_Humanoid.MoveToFinished:Connect(onWaypointReached) |
So, having redacted the mistake, I'll proceed to explain.
In the while loop, you are checking for the nearestPlayer
and "following" it with the function
followPath
, for now everything was good, but on Line 24, you were declaring the currentWaypointIndex
to be 1, constantly as it is inside of a while loop.
To counter this, we make currentWaypointIndex
a "global" in the scope of this script; Line 7.
This should fix your issue, any further questions DM me.
PS:Please accept this as an answer if this helped you.