- Home /
How to find a child from root?
Hi,
I have the following hiearchy:
Root
Child
Child 2
Child 3
Child 4
I have a code that's located on Child 4, and I need to find a variable on the first Child. I'm using this code, but I know that it isn't working:
Var1 = transform.root.Find("Child").GetComponent().Var2;
Is there any way to find the childs from the root?
Thanks
Be more specific than "it isn't working". What's the error message? Which part is null-referencing? Your sample snippet Var1 = transform.root.Find("Child").GetComponent().Var2;
obviously doesn't work because GetComponent
isn't taking any arguments or using the Generic GetComponent<$$anonymous$$yComponent>
version.
Answer by dannyskim · Jan 11, 2012 at 02:50 AM
http://unity3d.com/support/documentation/ScriptReference/Transform.Find.html
The link from the Unity Script Reference tells you how to traverse the hierarchy. So, assuming Root is a Game Object:
Root.transform.Find( "Child/Child 2/Child 3/Child 4" );
I left out the GetComponent call because I have no idea what you're trying to get. In c#, I believe you have to get the script as the component and then reference a variable as such:
Root.transform.Find( "Child/Child 2/Child 3/Child 4" ).GameObject.GetComponent<ScriptName>().Var2;
but that line of code is a guess, because I almost never use this deep of a search. Typically I'll have singletons that I reference that hold the variables through namespace calls.
Thanks for the answer, but it didn't worked :( It says: "error CS0103: The name `Root' does not exist in the current context"
$$anonymous$$y logic was the same as calling the parent of a transform. But ins$$anonymous$$d of using "transform.parent" I've tried to use "transform.root". But it didn't worked :(
Thanks again :)
Answer by enosoft · Nov 11, 2015 at 05:46 PM
Root Child Child 2 Child 3 Child 4
child4 = current transform child3 = transform.parent child2 = transform.parent.parent
can you test pls.