Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

"attempt to index nil with 'Position'" - Error?

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

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

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

This discussion is preserved as it was. New answers, comments, and votes are closed.