Attempt to index nil with 'Position'

I am getting this error:

Players.GreenTreeGamingYT.PlayerGui.EggSystem.ClientScripts.HatchClient:430: attempt to index nil with ‘Position’

Here is the function the error is coming from:

if not gameProcessed then
		if input.KeyCode == Enum.KeyCode.E then
			if player.Character ~= nil and isHatching == false then
				local nearestEgg
				local plrPos = player.Character.HumanoidRootPart.Position

				for i, v in pairs(Eggs:GetChildren())  do
					if nearestEgg == nil then
						nearestEgg = v
					else
						if (plrPos - v.PrimaryPart.Position).Magnitude < (nearestEgg.PrimaryPart.Position - plrPos).Magnitude then
							nearestEgg = v
						end
					end
				end

				if player:DistanceFromCharacter(nearestEgg.EggMesh.PrimaryPart.Position) < maxDisplayDistance then
					canHatch = true
				else
					canHatch = false
				end

				if canHatch == true then
					local result = replicatedStorage:WaitForChild("EggHatchingRemotes"):WaitForChild("HatchServer"):InvokeServer(nearestEgg)

					if result ~= "Cannot Hatch"  then
						if not cooldown then
							cooldown = true
							hatchOne(result, nearestEgg)
							wait(0.1)
							cooldown = false
						end
					end
				end
			end
		end

Erroring line:

if (plrPos - v.PrimaryPart.Position).Magnitude < (nearestEgg.PrimaryPart.Position - plrPos).Magnitude then

If you need any more code/things to help me. You can just reply.

Thanks

-GreenTreeGamingYT

Are you sure that v and nearestEgg has a primarypart? Try printing them out and check if they do. Cause the error says that you are indexing nil with .Position, and the only .Position used is on .PrimaryPart, which means at least one of them doesn’t have a PrimaryPart

1 Like

Got it thanks! One of the eggs didn’t have a primary part. Thanks for the help :smiley:

1 Like