Course contentsShow
← Unity Game Development
Lesson 101 of 8282. Scripting and LifecycleFree lesson

Managing Object Hierarchy at Runtime

Learners will programmatically reparent game objects by modifying the parent property of a Transform to dynamically change scene structure.

In this lesson, you will learn how to dynamically reorganize your scene structure by programmatically changing which object acts as the "parent" of another during gameplay.

Changing the Parent

In Unity, the hierarchy of your game is defined by the Transform component. Every GameObject has a transform, and every transform has a parent property. By default, an object might have no parent (making it a root object) or be attached to another object. To change this at runtime, you simply assign a new Transform to the parent property of your target object.

Think of this like a player picking up an item. When the player "grabs" a sword, the sword needs to move with the player. By setting the sword’s parent to the player’s hand transform, the sword becomes a child of that object.

Code Implementation

Here is how you can reparent an object using a script:

public class ObjectReparenting : MonoBehaviour
{
    public Transform newParent;

    void Start()
    {
        // Reassign the parent of this object to the new parent
        transform.SetParent(newParent);
    }
}

Important Considerations

When you change the parent property, the object’s localPosition, localRotation, and localScale are recalculated relative to the new parent's coordinate system. If your object suddenly jumps to a strange position after reparenting, it is usually because its localPosition is now being calculated from the origin of the new parent instead of the world center.

If you want the object to "snap" to the new parent’s position seamlessly, you can set the localPosition and localRotation to Vector3.zero and Quaternion.identity respectively immediately after changing the parent. This ensures the child sits exactly at the pivot point of its new parent.

This technique is incredibly powerful for inventory systems, interactive puzzles, or attaching visual effects to characters. By manipulating the parent property, you gain full control over how your game objects move and behave as a single unit throughout your scene’s lifecycle.

Key Takeaway: By assigning a new Transform to the parent property of an object’s transform component, you can dynamically rebuild your scene hierarchy while the game is running.