How can I stop this error from stopping my entire code?

Hi there, I have this script that involves the mouse and checks if the mouse.Target’s parent finds a child called Humanoid. The issue is, is that if I were to click on something that doesn’t have a parent, it throws an error saying attempt to index nil with ‘Parent’. I’ve already tried adding else statements, but my main priority is to make it so that the error doesnt break my entire code. Is there a way to do this?

else
		if dragging.Parent:FindFirstChild'Humanoid' then -- error is thrown
			for i, v in ipairs(dragging.Parent:GetChildren()) do
				if v:IsA'BasePart' then
					v.CanCollide = v:GetAttribute('CanCollide')
					v:SetAttribute('CanCollide',nil)
				end
			end
		else
			dragging.CanCollide = dragging:GetAttribute('CanCollide')
			dragging:SetAttribute('CanCollide',nil)
		end
	end

also, “dragging” is the mouse.Target

Add another if-statement checking if dragging isn’t nil.

1 Like

Wouldn’t I check if the parent is nil instead?

Nope, attempt to index nil is thrown when you try to index nil (dragging) with a string (Parent).

For example, this will throw the same error since a is nil:

local a = nil
a.Parent = workspace

Alright thanks it works now.

1 Like