Heya there.
I’ve decided to rewrite the entire script of a Pathfinding Module since I didn’t really like it. Anyway, there’s an issue that appeared which it kept spewing out “Attempting to Index nil on PrimaryPart” (In the RunService loop, I’m checking the distance between the enemy and the objective to be safe).
--[[SERVICES]]--
local PathfindingService = game:GetService("PathfindingService")
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
--[[MODULE]]--
local PathfindingModule = {}
function PathfindingModule.Pathfind(NPC, AggroRange)
--//Preperation
local Objective = game.Workspace:FindFirstChild("Crystal")
--Enemy
local RootPart = NPC.PrimaryPart
local Humanoid = NPC.Humanoid
local CharacterSize = NPC:GetExtentsSize()
RootPart:SetNetworkOwner(nil)
--//Pathfinding Agents
local PathfindingAgents = {
AgentRadius = (CharacterSize.X + CharacterSize.Z)/4,
AgentHeight = CharacterSize.Y,
AgentCanJump = true
}
--[[PATHFINDING]]--
local function FollowPath(Destination)
local NewPath = PathfindingService:CreatePath(PathfindingAgents)
NewPath:ComputeAsync(RootPart.Position, Destination)
if NewPath.Status == Enum.PathStatus.Success then
local Waypoints = NewPath:GetWaypoints()
for _, Waypoint in ipairs(Waypoints) do
if Waypoint.Action == Enum.PathWaypointAction.Jump then
Humanoid.Jump = true
end
--Just in case
NewPath.Blocked:Connect(function(blockedWaypointIdx)
print("The enemy's path is blocked. Recalculating.")
FollowPath(Objective.PrimaryPart.Position)
end)
Humanoid:MoveTo(Waypoint.Position)
local Timer = Humanoid.MoveToFinished:Wait(1)
if not Timer then
print("Path timed out. Recalculating.")
FollowPath(Objective.PrimaryPart.Position)
end
end
else
print("Path failed. Recalculating. Sorry.")
end
end
local function FindNearestTarget()
local Target = nil
local PlayerList = Players:GetPlayers()
for _, Player in pairs(PlayerList) do
local Character = Player.Character or Player.CharacterAdded:Wait()
if Character then
local Distance = (Character.PrimaryPart.Position - RootPart.Position).Magnitude
if Distance <= AggroRange then
Target = Character
end
else
warn(Player.Name.."'s Chararcter failed to load.")
end
end
return Target
end
RunService.Heartbeat:Connect(function()
local Target = FindNearestTarget()
print("My current target is "..Objective.Name)
--//Checking the distance again just to be safe.
local Distance = (Target.PrimaryPart.Position - RootPart.Position).Magnitude
if Target and Distance <= AggroRange then
Objective = Target
elseif not Target and Distance >= AggroRange then
Objective = game.Workspace:FindFirstChild("Crystal")
end
if Objective and Objective.PrimaryPart then
FollowPath(Objective.PrimaryPart.Position)
end
end)
end
return PathfindingModule