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'" - Error?

Asked by 2 years ago

Hi, am making a NPC turret that seraches for players then walks to them and kill them but am facing an error wich is the same as the title. Here is the code:

local myHuman = script.Parent:WaitForChild("Humanoid")
local myRoot = script.Parent:WaitForChild("HumanoidRootPart")
local myHead = script.Parent:WaitForChild("Head")
local headWeld = myHead:WaitForChild("HeadWeld")
local tip = script.Parent:WaitForChild("Tip")
local flash = tip:WaitForChild("Flash")

local myTeam = script.Parent:WaitForChild("Team")

--sounds
local shootSound = myHead:WaitForChild("Shoot")
local chargeSound = myHead:WaitForChild("Charge")

local clone = script.Parent:Clone()

local gunCool = true
local maxCharge = 10
local charges = maxCharge
local home = myRoot.Position

-- Error happens here
function checkDist (target)
    return (myRoot.Position - target.Position).Magnitude    
end

and here I defind the target :

function findTarget ()
    local dist = 100
    local target = nil
    for i,v in ipairs(workspace:GetChildren()) do
        local human = v:FindFirstChild("Humanoid")
        local torso = v:FindFirstChild("Torso") or v:FindFirstChild("HumanoidRootPart")
        local team = v:FindFirstChild("Team")
        if human and torso then
            if checkDist(target) < dist and human.Health > 0 then
                if team then
                    if team.Value ~= myTeam.Value then
                        dist = checkDist(target)
                        target = torso
                    end
                else
                    dist = checkDist(target)
                    target = torso
                end
            end
        end
    end
    return target
end

Any help is appreiciated !

2 answers

Log in to vote
0
Answered by 2 years ago
Edited 2 years ago

Anyways, thank you so much guys for who read this post I already figured the issue !!


function findTarget () local dist = 100 local target = nil for i,v in ipairs(workspace:GetChildren()) do local human = v:FindFirstChild("Humanoid") local torso = v:FindFirstChild("Torso") or v:FindFirstChild("HumanoidRootPart") local team = v:FindFirstChild("Team") if human and torso then if checkDist(torso) < dist and human.Health > 0 then if team then if team.Value ~= myTeam.Value then dist = checkDist(torso) target = torso end else dist = checkDist(torso) target = torso end end end end return target end
Ad
Log in to vote
0
Answered by
enes223 327 Moderation Voter
2 years ago

hey you! have you ever heard of enes? if you are in trouble, better call enes!

Answer this question