Attempt to index nil with 'Name'

so where it says “if p.name then” gives the error
image
even though in the line before it I print all the names

local PlacementEvent = game.ReplicatedStorage.PlacementEvent
local ObjectFolder = game.ReplicatedStorage:WaitForChild("ItemStorage")

PlacementEvent.OnServerEvent:Connect(function(Player,PreviewObject,ObjectCFrame)

	local Object = ObjectFolder:FindFirstChild(PreviewObject):Clone()
	
	
	Object:SetPrimaryPartCFrame(ObjectCFrame)
	Object.Parent = game.Workspace
	
	
	
	local function GetTouchingParts(part)
		local connection = part.Touched:Connect(function() end)
		local results = part:GetTouchingParts()
		connection:Disconnect()
		return results
	end

	local results = GetTouchingParts(Object.PrimaryPart)
	print(#results) --> 1
	
	for _, p in next, results do
		print(p.Name..' is touching '..Object.PrimaryPart.Name..'!')
		if p.Name == "PlotP" then
			print("on plot")
		else
			Object:Destroy()
		end
	end
	


end)

Interesting loop, is there any reason you don’t use something like pairs()?

for _, p in pairs(results) do
	... -- Code
end

Does the line before the error always print a proper value for p, or just mostly?

always printed proper values. didnt use pairs because i stole this off dev forum cause ive been having trouble with this for a while. just tried pairs and ipairs still have same issue.

if Object.PrimaryPart returns nil, that means the Object has no primary part

thats not whats causing the error. the line below it is.

Destroying a model sets the PrimaryPart to nil, so the next loop Object.PrimaryPart.Name will error.
Why is this here? Do you want the loop to end when this happens? If so, put a break after this line.

How can you expect us to know that? You don’t show line numbers or comment where the error is. If you paste the code into a text editor, this is line 25.
image
It also shouldn’t be possible for p to be nil so I doubt it’s the next line causing the error.

1 Like
	for _, p in ipairs(results) do
		print(p.Name..' is touching '..Object.PrimaryPart.Name..'!')
		if p.Name == "PlotP" then
			print("on plot")
			break
		else
			Object:Destroy()
			break
		end
	end

Ive done that now but it destroys the part anyway.
edit replied to wrong message oops

The error you posted says line 25.
Print p and Object.PrimaryPart at the start of the loop and see which one is nil.

It doesn’t end the loop, you need to use break for that.

else
    Object:Destroy()
    break
1 Like

figured it out yeaaaaaaaaaaaaaaaaa

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.