Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

✓ Accepted answer

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

1 comment

0

Alr thanks

This discussion is preserved as it was. New answers, comments, and votes are closed.