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

Transforming Objects Relative to Parent Coordinates

Learners will utilize localPosition and localRotation to ensure child objects maintain correct alignment when moving or rotating their parent.

In this lesson, you will learn how to precisely position and rotate child objects relative to their parent using localPosition and localRotation instead of world-space values.

Why Local Coordinates Matter

When you work with nested objects in the Unity Hierarchy, you might notice that a child's Transform component displays values that look different from what you see in the Scene view. This is because those values are local.

If you use transform.position in a script, Unity calculates the object's location relative to the center of the entire world (0,0,0). However, if you want a child object (like a character’s sword) to stay attached to a parent (the character’s hand) regardless of where the parent moves, using world coordinates becomes a math nightmare. Instead, we use localPosition and localRotation. These properties define where the object sits in relation to its parent’s "anchor" point.

Putting it into Code

Imagine you want to programmatically reset a held item to the center of the parent object’s grip. You can set these properties directly in your script:

void ResetToParentGrip()
{
    // The child will snap exactly to the parent's pivot point
    transform.localPosition = Vector3.zero;
    
    // The child will align its rotation perfectly with the parent
    transform.localRotation = Quaternion.identity;
}

By assigning Vector3.zero to localPosition, you aren't moving the object to the center of the game map; you are telling Unity to place the object exactly where the parent is located. Similarly, Quaternion.identity for localRotation removes any rotation offset, making the child look in the exact same direction as the parent.

This approach is highly efficient for gameplay mechanics like mounting items, attaching accessories, or handling character equipment. Since these values are relative to the parent, moving or rotating the parent automatically carries the child along, preserving the relationship you defined without you needing to update the child’s position every frame.

Key Takeaway: Use localPosition and localRotation to define an object’s orientation relative to its parent’s origin, ensuring your objects maintain consistent alignment even when the parent moves through the game world.