Game Development Reference
In-Depth Information
Accessing object hierarchies
The Hierarchy panel in Unity offers a graphical illustration of the parent-child
relationship that holds among all GameObjects in a scene. This relationship is
important because child objects are contained by, and inherit, the transformations
of their parents. However, being able to define and edit the hierarchical relationship
in the editor is usually not enough. You'll frequently need to parent one object to
another in code and also cycle through all children of a specified object to process
data or invoke functionality on them. Let's first see how to parent objects. The
following code sample 3-8 demonstrates how to attach one object X to another
object Y as its child, through the Transform component:
using UnityEngine;
using System.Collections;
//----------------------------------------------------
public class Parenter : MonoBehaviour
{
//Reference to child object in scene
private GameObject Child;
//Reference to parent object in scene
private GameObject Parent;
//----------------------------------------------------
// Use this for initialization
void Start ()
{
//Get parent and child objects
Child = GameObject.Find("Child");
Parent = GameObject.Find("Parent");
//Now parent them
Child.transform.parent = Parent.transform;
}
//----------------------------------------------------
}
//----------------------------------------------------
 
Search WWH ::




Custom Search