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

How do I check to see if the parent of an object is nil?

Asked by
P100D 590 Moderation Voter
9 years ago

I forgot how to do it. I need my script to not act if the parent of the hit object is nil, because otherwise it returns an error.

Here's my script.

function onTouched(hit)
    if hit.Parent.Name == "Monorail" then
        local explosion = Instance.new("Explosion")
        explosion.Parent = hit
        explosion.Position = hit.Position
        wait(0.5)
        hit:remove()
        wait(5)
        hit.Parent:remove()
    end
end

script.Parent.Touched:connect(onTouched)

1 answer

Log in to vote
1
Answered by
Mystdar 352 Moderation Voter
9 years ago

I don't think the lack of parent is the problem, it is because hit is removed, so it no longer has a parent, because it no longer exists, because you removed it. To fix this make a variable of the parent before hit is removed.

function onTouched(hit)
    if hit.Parent.Name == "Monorail" then
        local explosion = Instance.new("Explosion")
        explosion.Parent = hit
        explosion.Position = hit.Position
        wait(0.5)
        local parent = hit.Parent -- This should do it
        hit:remove()
        wait(5)
        parent:remove()
    end
end

script.Parent.Touched:connect(onTouched)
0
For bullets, `hit.Parent` *can* be `nil`, so it is good for your health to check for `hit.Parent` before using it in an onTouched script.  BlueTaslem 18071 — 9y
0
Also, USE A LOCAL VARIABLE! Or else this script won't be very useful! BlueTaslem 18071 — 9y
Ad

Answer this question