unity3d Transforms Parenting and Children


Example

Unity works with hierarchies in order to keep your project organized. You can assign objects a place in the hierarchy using the editor but you can also do this through code.

Parenting

You can set an object's parent with the following methods

var other = GetOtherGameObject();
other.transform.SetParent( transform );
other.transform.SetParent( transform, worldPositionStays );

Whenever you set a transforms parent, it will keep the objects position as a world position. You can choose to make this position relative by passing false for the worldPositionStays parameter.

You can also check if the object is a child of another transform with the following method

other.transform.IsChildOf( transform );

 

Getting a Child

Since objects can be parented to one another, you can also find children in the hierarchy. The simplest way of doing this is by using the following method

transform.Find( "other" );
transform.FindChild( "other" );

Note: FindChild calls Find under the hood

You can also search for children further down the hierarchy. You do this by adding in a "/" to specify going a level deeper.

transform.Find( "other/another" );
transform.FindChild( "other/another" );

Another way of fetching a child is using the GetChild

transform.GetChild( index );

GetChild requires an integer as index which must be smaller than the total child count

int count = transform.childCount;

 

Changing Sibling Index

You can change the order of the children of a GameObject. You can do this to define the draw order of the children (assuming that they are on the same Z level and the same sorting order).

other.transform.SetSiblingIndex( index );

You can also quickly set the sibling index to either first or last using the following methods

other.transform.SetAsFirstSibling();
other.transform.SetAsLastSibling();

 

Detaching all Children

If you want to release all children of a transform, you can do this:

foreach(Transform child in transform)
{
    child.parent = null;
}

Also, Unity provides a method for this purpose:

transform.DetachChildren();

Basically, both looping and DetachChildren() set the parents of first-depth children to null - which means they will have no parents.

(first-depth children: the transforms that are directly child of transform)