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

"attempt to index a nil value"? Help please!

I wanted to make a brick that removes current tool that player is holding. I made this script:

function onTouched(hit)
	if hit.Parent:findFirstChild("Tool").Name == "Gun" then
		local gun = hit.Parent.findFirstChild("Tool").Name
		gun:Destroy()
	end
end

script.Parent.Touched:connect(onTouched)

And it doesn't work! Can someone help me?

2 comments

1

u cant destroy a name

1

In line 2 you basically telling the script the Search for a object NAME "Tool" then you are telling script if Object you find is name "Tool" and that name is the same as "Gun" (which is can't be because common sense tells us otherwise) then continue.... Do you get where I'm going here?!?! What you're writing in line 2 doesn't make whole lot of sense.

1 answer

Your Problem

You're not destroying the tool instance! When you defined 'gun' on line 3, you indexed the Name Property. By doing this, 'gun' is a string, corresponding to the name of the first found child in the directory of your Backpack, named "Tool". So, if such tool was ever found then 'gun' is ALWAYS only ever going to be a string, "Tool".


How To Fix

1) Rather than using the FindFirstChild function in a conditional, you should iterate through the Character's descendants. This is necessary due to the fact that any equipped tool is Parented into the Character.

2) Don't check for the name of the tool, since if you make other tools and want to name them other things then they would not pass the conditional. Check for the Class. You can either use the IsA function or the ClassName property to determine whether or not the current iteration is a tool.

3) Define 'gun' as the actual tool! Not the Name Property of the tool!


Code

function onTouched(hit)
	--Check for a humanoid
	if hit.Parent:FindFirstChild("Humanoid") then
		--Iterate through the character
		for _,v in next, hit.Parent do
			--Check if current iteration is a tool
			if v:IsA("Tool") or v:IsA("HopperBin") then
				--Destroy the tool
				v:Destroy()
			end
		end
	end
end

script.Parent.Touched:connect(onTouched)

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