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.
If I do an if statement to check if something exist, I wouldn't do this,
if workspace.Head then-- error end
Because, if Head doesn't exist, you would get the error, Attempt to Access a nil value, "Head"
.
You should use FindFirstChild
. If the function FindFirstChild doesn't find what it's looking for, it doesn't error, it just returns nil.
if whatTouched.Parent:FindFirstChild("Humanoid") or whatTouched.Parent.Parent:FindFirstChild("Humanoid") or whatTouched.Parent.Parent.Parent:FindFirstChild("Humanoid") then child:Destroy() end
FindFirstChild
has an optional parameter that will search though all the descendants. Example,
workspace:FindFirstChild("Head",true)
Your code,
if whatTouched.Parent.Parent.Parent:FindFirstChild("Humanoid", true) then --Ect end
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!