- Home /
A quick way to find the root parent?
For example,there's an object contains a lot of children,like:
Person -> Body -> Hands -> Finger(Add a box collider component for Finger object);
and when the Finger hit by a Bullet for example,
How to find "Person" object in a quickl way , not to use "collider.transform.parent.parent.parent" ect....
thx...
Answer by syclamoth · Oct 14, 2011 at 06:29 AM
Instead, you use the handy shortcut
collider.transform.root;
This always returns the highest transform in the hierarchy!
Awesome, I did not know that! Ill add it to my solution also but the poster of this question should mark your answer as the right one!
Ha, This simple script shows me I'm lazy to look for the document!!!!
Thx!
Note: it may not be ideal to use the root like this, as you come a cropper if you start parenting objects to others! Speaking from experience here ;)
Answer by PatrikNyblad_SI · Oct 14, 2011 at 06:31 AM
My approach would have been to cache the Person Transform or GameObject in Finger.
private var person : Transform;
function Start () {}
person = transform.parent.parent.parent;
}
Another way to get the person would be to use GameObject.Find() like this:
person = GameObject.Find("/Person");
But this assumes you have the Person object in the root of your scene since I put a "/" before the "Person" and this is just to make the find faster, otherwise it will search through your whole hierarchy of objects. This will of course limit you to only have one Person object in your scene.
GameObject.Find Manual: http://unity3d.com/support/documentation/ScriptReference/GameObject.Find.html
And just as a tips when developing for iPhone and getting components attached to objects through code witch i guess you want to do to apply damage to Person in a script, you should get the component like this:
GetComponent.<ScriptName>();
Another even simple way to do things suggested by "syclamoth" is:
transform.root
Hope it helps!
Thank you the same for such a detail description,it makes me learn more things.