- Home /
Raycast Get Object Using Empty GameObjects in Hierarchy
I am using empty gameobjects to organize my hierarchy and have a raycast grabbing objects in the world that are childs of the empty gameobjects (for organization purposes).
I want to get the root of the gameobject when the raycast hits it. The problem is that since I am grouping objects in empty gameobjects, "collider.transform.root" returns the empty gameobject used for organization.
How can I get the main parent gameobject from the raycast without getting the holder gameobject?
For any given transform, you can check its parent all the way up to the top of the hierarchy (at which point the parent will be null
).
So, really, the question is: what does "main parent" mean to you? If you can figure that out, just keep going one parent up until you find it.
If your main parent has a unique name and is a direct child of the root you can do:
var mainParent = transform.root.Find("UniqueName");
Thank you both. I feel like robertbu's answer is a good implementation of rutter's. Thanks again!
This is more what I though @rutter was talking about. If you have multiple main parents collected under an empty game object, this will work better, since it does not require a name:
function Find$$anonymous$$ainParent(start : Transform) : Transform {
var parent : Transform;
var child : Transform = start;
var curr = start;
while (curr.parent != null) {
parent = curr.parent;
child = curr;
curr = parent;
}
return child;
}
Cannot be called form the root.
Huh, calling Find from the root is a nice and quick method, though. I'll have to remember that.