Menu
CoddyTech

Parents and Children

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 24 of 67.

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

The Flag is a child of the Ship, and the ship is not at the center of the world. The flag's Start() means to put it at the foot of the mast, 0.6 to the right and 1 up measured from the ship, but it writes those numbers to position, so the flag lands away from the ship.

  • Fix Start() so the flag starts at the foot of the mast.
  • While the up arrow is held, hoist the flag: it climbs at climb units per second until its height measured from the ship is 4, the top of the mast, and stops there.

Press Play, hold the up arrow, 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
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics