Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

15:25:36.732 - Workspace..MoveTo:22: attempt to index nil with 'HumanoidRootPart'?

Asked by 3 years ago
Edited 3 years ago

I'm working on making a pathfinding following NPC, however it never seems to be able to access the target's humanoid root part. I'm not sure if the target is nil or something, but whatever it is, it's really annoying. Help much appreciated

EDIT: Target is not nil, it recoginises that I am the closest player, yet it can't find my target's character. Maybe something to do with the script running before I join?

local PathfindingService = game:GetService("PathfindingService")
local Humanoid = script.Parent.Humanoid
local HumanoidRootPart = script.Parent.HumanoidRootPart
local MaxDistance = 200
function FindClosestTarget(MaxDist, TableOfCurrentPlayers)
    local Target
    local SmallestDistance = MaxDist
    local PlayerWithSmallerDistance
    for _, player in pairs(TableOfCurrentPlayers) do
        local distance = player:DistanceFromCharacter(HumanoidRootPart.Position)
        if distance < SmallestDistance then
            SmallestDistance = distance
            PlayerWithSmallerDistance = player
        end
    end
    Target = PlayerWithSmallerDistance
    return Target
end

function FindAndMoveToTargetPos()
    local Target = FindClosestTarget(MaxDistance, game.Players:GetPlayers())
    local Target_HRP = Target.Character.HumanoidRootPart
    local path = PathfindingService:CreatePath()
    path:ComputeAsync(HumanoidRootPart.Position, Target_HRP.Position) 
    local waypoint = path:GetWaypoints()
    for i, waypoint in pairs(waypoint) do
        if waypoint.Action == Enum.PathWaypointAction.Jump then 
            Humanoid.ChangeState(Enum.HumanoidStateType.Jumping)
        end
        Humanoid:MoveTo(waypoint.Position) 
        Humanoid.MoveToFinished:Wait(.1) 
    end
end

while wait(.1) do
    FindAndMoveToTargetPos()
end

1 answer

Log in to vote
2
Answered by
Rare_tendo 3000 Moderation Voter Community Moderator
3 years ago
Edited 3 years ago

It didn't find the closest player's character apparently. So you will have to check if the character exists

local TargetChar = Target.Character
if TargetChar then
    -- run code
end
0
Alr thanks JeffTheEpicRobloxian 258 — 3y
Ad

Answer this question