Attempt to index nill with position

  1. What do you want to achieve? I want to achieve the following script

  2. What is the issue? It is printing in output "Attempt to index nill with position

  3. What solutions have you tried so far? I tried many editions of code and also I asked in discord server how to fix it

script

local NPC = script.Parent

local SelfHum = script.Parent.Humanoid

local SelfHRP = script.Parent.Torso

while wait(1) do
	
	for i, v in pairs(workspace:GetChildren()) do
		
		if v:FindFirstChild("Humanoid") and v~= NPC then
			
			local PeopleHRP = v:FindFirstChild("HumanoidRootPart")
			
			local magnitude = (SelfHRP.Position - PeopleHRP.Position).Magnitude
			
			if magnitude <= 100 and v~= NPC then
				
				SelfHum:MoveTo(PeopleHRP.Position)
				
			else

				SelfHum:MoveTo(Vector3.new(math.random(1,100),1,math.random(1,100)))
				
			end
			
			
		end
		
	end
	
end

Line error is 15

			local magnitude = (SelfHRP.Position - PeopleHRP.Position).Magnitude

It is also working on one npc but on the other the script is printing error

Have you checked if SelfHRP becomes nil?

Edit : Are you sure your NPC model has a Torso and not a HumanoidRootPart?

Yes, the script is working on one npc but on another npc it is not working

You’re loopong through workspace and looking for a humanoidRootPart, but not all objects in workspace have this item. So when you try to define PeopleHRP, it returns nil because it doesn’t exist. What i suggest you do is right after you define the PeopleHRP, you add an if statement that checks if it exist.

if PeopleHRP then
      --- continue rest here
end 

You may also wanna check if its a basePart depending on if you have other objects which aren’t parts named HumanoidRootPart.

1 Like

You explained it perfectly and it is also working thanks for the help :smiley: