I have a script inside an npc that is supposed to move towards this goal. It does that, but it doesn’t auto updates so if the goal moves the npc will go to its original place not the place it is in currently.
local PathfindingService = game:GetService("PathfindingService")
local Humanoid = script.Parent.Humanoid
local Root = script.Parent:FindFirstChild("HumanoidRootPart")
local goal = game.Workspace.Test.Position
local path = PathfindingService:CreatePath()
path:ComputeAsync(Root.Position, goal)
local waypoints = path:GetWaypoints()
wait()
for i, waypoint in ipairs(waypoints) do
path:ComputeAsync(Root.Position, goal)
local waypoints = path:GetWaypoints()
Humanoid:MoveTo(waypoint.Position)
if waypoint.Action == Enum.PathWaypointAction.Jump then
Humanoid.Jump = true
end
Humanoid.MoveToFinished:Wait()
end
You need to recompute the path using ComputeAsync. It’s up to you how often you want to update this and when. Keep in mind that the more you call ComputeAsync, the more work your script is doing, which scales with the number of NPCs you have.
If you’re just looking to update the path anytime the goal’s position changes you could do:
local PathfindingService = game:GetService("PathfindingService")
local Humanoid = script.Parent.Humanoid
local Root = script.Parent:FindFirstChild("HumanoidRootPart")
local goal = game.Workspace.Test -- Changed this to the object rather than just the Position
local path = PathfindingService:CreatePath()
local function UpdatePath()
path:ComputeAsync(Root.Position, goal.Position)
local waypoints = path:GetWaypoints()
task.wait() -- Replaced "wait" as "task.wait" is more accurate
for i, waypoint in ipairs(waypoints) do
path:ComputeAsync(Root.Position, goal)
local waypoints = path:GetWaypoints()
Humanoid:MoveTo(waypoint.Position)
if waypoint.Action == Enum.PathWaypointAction.Jump then
Humanoid.Jump = true
end
Humanoid.MoveToFinished:Wait()
end
end
UpdatePath() -- Updates the path
goal:GetPropertyChangedSignal("Position"):Connect(UpdatePath) -- Calls UpdatePath function when goal's Position property changes