So im working on a game and im trying to get an NPC to follow a player around the map. So far i have this script going.
local NPC = game.Workspace.Matt
local pathfinding_service = game:GetService("PathfindingService")
function getClosestPlayer()
local closest_player, closest_distance = nil, 200
for i, player in pairs(workspace:GetChildren()) do
if player:FindFirstChild("Humanoid") and player ~= NPC then
local distance = (NPC.PrimaryPart.Position - player.PrimaryPart.Position).Magnitude
if distance < closest_distance then
closest_player = player
closest_distance = distance
end
end
end
return closest_player, closest_distance
end
while true do
local path = pathfinding_service:CreatePath()
local player, distance = getClosestPlayer()
if player and distance > 10 then
path:ComputeAsync(NPC.HumanoidRootPart.Position, player.PrimaryPart.Position)
local waypoints = path:GetWaypoints()
for _, waypoint in pairs(waypoints) do
NPC.Humanoid.MoveTo(Waypoint.Position)
while true do
local distance = (NPC.PrimaryPart.Position - waypoint.Position).Magnitude
local distance_from_player = (NPC.PrimaryPart.Position - player.PrimaryPart.Position).Magnitude
if distance < 5 then
break
end
if distance_from_player < 10 then
NPC.Humanoid:MoveTo((NPC.HumanoidRootPart.CFrame*CFrame.new(0,0,-3)).p)
break
end
wait()
end
end
end
wait()
end
It is giving me this in the output
Workspace.Matt.Follow the Player:8: attempt to index nil with 'Position'
this is the line it is referencing
local distance = (NPC.PrimaryPart.Position - player.PrimaryPart.Position).Magnitude
If anyone has any idea how to fix this issue, let me know please! thanks!

5 comments
Try using the HumanoidRootPart instead of the primary part (NPC.HumanoidRootPart and player.HumanoidRootPart)
would i replace all PrimaryPart with what you suggested in the script?
PrimaryPart only works with models, ensure that NPC is a model
Re-edited check my answer, this will work.
also remove any other script in the model, except your script or scripts.