Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Attempt to index nil with 'Position'?

Asked by
naturedat 124
3 years ago
Edited 3 years ago

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 answer

Log in to vote
2
Answered by
Necro_las 412 Moderation Voter
3 years ago
Edited 3 years ago

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
0
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! naturedat 124 — 3y
Ad

Answer this question