I’m trying to make a pathfinding system for NPC’s where they reach the end position using predefined nodes, I have this so far but it stops randomly with no errors or anything. Not sure why it does this.
Here’s the code -
local PathfindingService = game:GetService("PathfindingService")
local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")
local nodeFolder = workspace.Nodes
local nodePositions = {}
for _, nodePart in ipairs(nodeFolder:GetChildren()) do
if nodePart:IsA("BasePart") then
table.insert(nodePositions, nodePart.Position)
end
end
local path = PathfindingService:CreatePath()
local function followPath(destination)
local success, errorMessage = pcall(function()
path:ComputeAsync(character.PrimaryPart.Position, unpack(nodePositions), destination)
end)
if success and path.Status == Enum.PathStatus.Success then
local waypoints = path:GetWaypoints()
local moveFinishedEvent = Instance.new("BindableEvent")
local moveFinishedConnection
-- Move NPC along the path
for i, waypoint in ipairs(waypoints) do
moveFinishedConnection = humanoid.MoveToFinished:Connect(function(reached)
if reached then
moveFinishedEvent:Fire()
end
end)
humanoid:MoveTo(waypoint.Position)
moveFinishedEvent.Event:Wait()
moveFinishedConnection:Disconnect()
end
moveFinishedEvent:Destroy()
else
warn("Path not computed!", errorMessage)
end
end
local destination = Vector3.new(nodeFolder.End.Position)
followPath(destination)
Here’s a video -