Menu
CoddyTech

Parents and Children

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 31 of 85.

In the Hierarchy, an object dragged onto another becomes its child and is shown indented under its parent. A child moves, turns and scales with its parent: move the parent and every child comes along, with no code on the children.

Unity stores a child's place relative to its parent. transform.localPosition is that offset, measured from the parent; transform.position is the place in the world. This Rider is a child of a Horse, and its script seats it 1 unit above the horse's center and half a unit back, wherever the horse stands:

void Start()
{
    transform.localPosition = new Vector3(0, 1, -0.5f);
}

With the horse at (4, 0.5, 2), the rider's position reads (4, 1.5, 1.5) while its localPosition stays (0, 1, -0.5). When the horse walks on, position changes and localPosition does not. The offset is measured along the parent's own axes, so when the parent turns or is scaled, the offset turns and scales with it. For an object with no parent, localPosition and position are the same.

challenge icon

Challenge

Medium

Put the flag at the foot of the mast, measured from its ship.

  1. In Start(), the numbers (0.6, 1, 0) are measured from the Ship, the flag's parent.
  2. On that line, change transform.position to transform.localPosition.

Press Play: the flag sits at the foot of the mast, on the ship. Then Check.

Try it yourself

using UnityEngine;

public class Hoist : MonoBehaviour
{
    public float climb = 1f;

    void Start()
    {
        // The foot of the mast: 0.6 right and 1 up, measured from the Ship
        transform.position = new Vector3(0.6f, 1, 0);
    }

    void Update()
    {
        // While the up arrow is held, climb until the height from the Ship is 4
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground