In which case this code snippet may throw error "Attempt to index nil with :IsA()?"

I have wrote this code as part of a more complex system. But I genuinely can’t understand in which case New.Parent will be nil?

Data[Player].Connections.CharacterChildAdded = Character.DescendantAdded:Connect(function(New)
	if New.Parent:IsA("Accessory") and New:IsA("BasePart") then
		New.CanCollide = false
		New.CanQuery = false
		New.CanTouch = false
	end
end)

New.Parent will be nil if you’ve set the Parent to nil (you probably didn’t) or if New was destroyed. You’ve likely destroyed the New thing somewhere in a different script

EDIT taking another look I’m probably wrong about this..

After hours of debugging, I have found that it was caused by TouchInterest instance. Weird. I can’t even see it.

The only time this error occurs in this context is if Parent is nil at the moment DescendantAdded fires.

Wonder if this would catch both instances.. (it should)

Data[Player].Connections.CharacterChildAdded = Character.DescendantAdded:Connect(function(New)
    local parent = New.Parent or New.AncestryChanged:Wait()
    if New:IsA("BasePart") and parent:IsA("Accessory") then
        New.CanCollide = false
        New.CanQuery = false
        New.CanTouch = false
    end
end)
2 Likes

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