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!