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

Attempt to index nil with 'Position'?

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

✓ Accepted answer

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

1 comment

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!

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