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

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

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

✓ Accepted answer

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.

1 comment

0

Switched my answers there xD

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