Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 8 years ago

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?

1
u cant destroy a name koolkid8099 705 — 8y
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. UserOnly20Characters 890 — 8y

1 answer

Log in to vote
2
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
8 years ago

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)
Ad

Answer this question