Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Why Does This Hat Remover Script Give Me an Error? (SOLVED)

When I play solo in Studio, after a few seconds the debugger kicks in, and tells me that there's an error in a script. It's a hat removing script parented to a part. When I touch it w/ my character, it removes all of my hats. Even though it does its job without any problems, I still get this error:

Error | attempt to index field 'Parent' (a nil value)

This is the code:

function onTouched(hit) 
	local d = hit.Parent:GetChildren() 
	for i=1, #d do 
		if (d[i].className == "Hat") then 
			d[i]:remove() 
		end 
	end
end 

script.Parent.Touched:connect(onTouched) 

Can any1 tell me what's wrong?

1 answer

Gosh, I figured it out. The part this script was parented to was touching another part(a part that didn't have a parent, hence the error), so the function was being called even when my character wasn't touching the hat remover. To fix, just check if "hit" has a parent.

function onTouched(hit)
	if not hit.Parent then
		return nil
	elseif hit.Parent then
		local d = hit.Parent:GetChildren() 
		for i=1, #d do 
			if (d[i].className == "Hat") then 
				d[i]:remove() 
			end 
		end
	end
end 

script.Parent.Touched:connect(onTouched) 

2 comments

0

remove is depreciated. Use Destroy() instead.

0

There is a difference in remove and destroy.

This discussion is preserved as it was. New answers, comments, and votes are closed.