Get Transform

I have a prefab with script attached to the root.

the preafab has a lot of children as you ca see in picture below.

How ca i get a child tronsform in the script attached to the root ? For example of the “gun” child which is one of the far way child from the root ?

In c# i know how to do it but i have no idea how to do it in javascript.

[70242-безымянныи.png|70242]

I’ve had similar problem once, getting the right transforms and filtering them. I ended up writing my data structure class which mimics transform hierarchy. From that point i had methods to filter or find whatever i want.

I made this extension method. May be slow, but if it’s only called in awake that shouldn’t be much of a problem.

public static Transform GetChild(this Transform transform, string name)
	{
		Transform[] arr = transform.gameObject.GetComponentsInChildren<Transform> ();
		foreach(Transform t in arr)
		{
			if(t.gameObject.name == name)
			{
				return t;
			}
		}
		return null;

	}

Edit: Whoops! Didn’t notice you wanted JS. Hopefully this will help somebody else.

Edit2: Nevermind, you can use extension methods in JavaScript if you put the C# file in a “Plugins” folder. Create a C# file with that extention method, create a folder call ‘Plugins’, and place the file inside it. You can then reference it in your JavaScripts.

transform.root
Will give you the Uber-Parent object in any tree.

Anywhere in your screenshotted hierarchy, transform.root would be soldier3rdPerson.

From there you use the search methods on transform class to Find the children. (Which is a common question)

First of all the Transform.Find method returns a transfrom, so calling .transform after Find is pointless. You could simply do Find("xxx").Find("yyy");

However The Find method allows you to specify a “path” as well:

Transform gun = transform.Find("soldierCharacter/Bip01/Bip01 Pelvis/Bip01 Spine/Bip01 Spine1/Bip01 Spine2/Bip01 Neck/Bip01 R Clavicle/Bip01 R UpperArm/Bip01 R Forearm/Bip01 R Hand/gun");

While this is possible it’s usually not a good approach. It’s better to define a public variable in your root script and assign the gun transform in the inspector to that variable.

public Transform gun;

Another dynamical way is to “search” for a known Component. For example if you attach a component to your “gun” transform which is called “GunSlot” you can simply do

gun = GetComponentInChildren<GunSlot>().transform;

GetComponentInChildren will search for any component in any children.

Another way would be to use GetComponentsInChildren<Transform>() (note the Components) and iterate over all transforms to filter out the one you need. You could use a for loop or Linq:

using System.Linq;

gun = GetComponentsInChildren<Transform>().Where(t=>t.name).FirstOrDefault();