I'm basically just making an enemy npc that goes to the nearest npc in the game and attack each other. This script is located in the npc. The error is in line 29. Help please:
local dis = math.huge
local rot = script.Parent.HumanoidRootPart.Position
local animation = script:WaitForChild("Animation")
local hold = script:WaitForChild("Hold")
local human = script.Parent:WaitForChild("Humanoid")
local ani = human:LoadAnimation(animation)
local anima3 = human:LoadAnimation(hold)
anima3:Play()
ani:Play()
function findNearestHumanoid(pos)
local list = game.Workspace:GetChildren()
for i = 1,#list do
local v = list[i]
if v.ClassName == "Model" and v ~= script.Parent then
local rootpart = v:FindFirstChild("HumanoidRootPart")
local humanoid = v:FindFirstChildWhichIsA("Humanoid")
if humanoid ~= nil and rootpart and humanoid.Health <= 0 then
if (rootpart.Position - pos).Magnitude < dis then
local space = rootpart
return space
end
end
end
end
end
while true do
wait(1)
local map = findNearestHumanoid(rot).Position - rot -- Attempt to index nil with 'Position' here
local mag = map.Magnitude
if mag < 3 then -- th NPC stops when they get close enough
ani:Stop()
else
ani:Play()
end
local target = findNearestHumanoid(script.Parent.HumanoidRootPart.Position)
if target ~= nil then
script.Parent:FindFirstChildWhichIsA("Humanoid"):MoveTo(target.Position)
end
end
Thank you!

1 comment
Thanks, I actually found out why the function returned nil, it was because on line 18, humanoid.Health <= 0 so it was a stupid mistake but thanks!