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

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

Asked by 9 years ago

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:

01function onTouched(hit)
02    local d = hit.Parent:GetChildren()
03    for i=1, #d do
04        if (d[i].className == "Hat") then
05            d[i]:remove()
06        end
07    end
08end
09 
10script.Parent.Touched:connect(onTouched)

Can any1 tell me what's wrong?

1 answer

Log in to vote
0
Answered by 9 years ago

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.

01function onTouched(hit)
02    if not hit.Parent then
03        return nil
04    elseif hit.Parent then
05        local d = hit.Parent:GetChildren()
06        for i=1, #d do
07            if (d[i].className == "Hat") then
08                d[i]:remove()
09            end
10        end
11    end
12end
13 
14script.Parent.Touched:connect(onTouched)
0
remove is depreciated. Use Destroy() instead. ChemicalHex 979 — 9y
0
There is a difference in remove and destroy. FiredDusk 1466 — 9y
Ad

Answer this question