Script not being able to get HumanoidRootPart of a player's character

I’m trying to make an NPC detect the closest player and chase them using each player’s HumanoidRootPart, but I’m getting this error every time:

Workspace.stalker.chase:15: “Attempt to index nil with ‘HumanoidRootPart’”

I tried to get the player’s torso instead, but it doesn’t work with any object.

This is the script:

local rs = game.ReplicatedStorage

local forbidden = rs:WaitForChild("Forbidden")
local ai = require(forbidden:WaitForChild("AI"))

local npc = script.Parent

local closestdist = 1000000000000000
local closestplr = nil

game["Run Service"].Stepped:Connect(function()
	for _, plr in game.Players:GetPlayers() do
		if (plr.Character.HumanoidRootPart.Position - script.Parent.HumanoidRootPart.Position).Magnitude < closestdist then
			closestdist = (plr.Character.HumanoidRootPart.Position - script.Parent.HumanoidRootPart.Position).Magnitude
			closestplr = plr
			script.Parent.currentPlr.Value = plr
		end
	end
	
	if closestplr == not script.Parent.currentPlr.Value then
		ai.SmartPathfind(npc, closestplr, false, {Visualize = false, Tracking = true})
	else
		if closestplr == script.Parent.currentPlr.Value then
			-- do nothing so it still chases the same player so the pursuit is silky smooth. ignore this btw
		end
	end
end)

If anyone knows how to fix this or what I’m getting wrong, please let me know, thank you in advance!

The player takes longer to load in than the server, so the humanoidrootpart might not exist when your script runs.

For this, you can do

for _, plr in game.Players:GetPlayers() do
        local character = plr.Character -- Could do plr.CharacterAdded:Wait() to wait until the charcter exsitsts, but we'd slow down the code with that
        local HumanoidRootPart = character and character:FindFirstChild("HumanoidRootPart") -- if character, then we try to find the rootpart, then in the next if state ment we add a check to see if the rootpart has been found or not
		if  HumanoidRootPart and (HumanoidRootPart.Position - script.Parent.HumanoidRootPart.Position).Magnitude < closestdist then
			closestdist = (HumanoidRootPart.Position - script.Parent.HumanoidRootPart.Position).Magnitude
			closestplr = plr
			script.Parent.currentPlr.Value = plr
		end
	end
1 Like

What “Attempt to index nil with ‘HumanoidRootPart” means, is that you tried to index something that doesnt exist with “HumanoidRootPart”. In other words, its not the humanoid root part that doesnt exist, its the character itself.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.