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!
Your function findNearestHumanoid() can return nil if there is no one near, and then you cant get nil.Position. I recomend creating a variable to check its presence, like:
local nearestHumanoid = findNearestHumanoid(rot) local map if nearestHumanoid then map = nearestHumanoid.Position - rot end