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

Is there a more efficient way to tell if an object's parent (grandparent, etc.) has an object?

Asked by
Klamman 220 Moderation Voter
7 years ago

I'm writing a short script and I often find myself checking to see if an object has a parent that contains a Humanoid.

if whatTouched.Parent.Humanoid or whatTouched.Parent.Parent.Humanoid or whatTouched.Parent.Parent.Parent.Humanoid then
            child:Destroy()
        end
end

Is there a more efficient and less redundant way of making this check? Thanks.

1 answer

Log in to vote
0
Answered by 7 years ago
Edited 7 years ago

First problem,

If I do an if statement to check if something exist, I wouldn't do this,

if workspace.Head then-- error

end

Why not?

Because, if Head doesn't exist, you would get the error, Attempt to Access a nil value, "Head".

What should I do?

You should use FindFirstChild. If the function FindFirstChild doesn't find what it's looking for, it doesn't error, it just returns nil.

Your code,

if whatTouched.Parent:FindFirstChild("Humanoid") or whatTouched.Parent.Parent:FindFirstChild("Humanoid") or whatTouched.Parent.Parent.Parent:FindFirstChild("Humanoid") then
    child:Destroy()
end
I know, this makes the code longer but it's necessary.

Your Question,

FindFirstChild has an optional parameter that will search though all the descendants. Example,

workspace:FindFirstChild("Head",true)
true sets the function to look though all children, grandchildren, ect

Your code,

if whatTouched.Parent.Parent.Parent:FindFirstChild("Humanoid", true) then
    --Ect
end

Final Code,

if whatTouched.Parent.Parent.Parent:FindFirstChild("Humanoid", true) then
    child:Destroy()
end

You also had and extra end but I'm sure this is just a portion of the code.

I hope this helps you somehow.

Good Luck!

Yes, I admit, I first posted a no, but the answer really is no. This does not make the code more "efficient", only shorter.
0
Switched my answers there xD User#11440 120 — 7y
Ad

Answer this question