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
MediumPut the flag at the foot of the mast, measured from its ship.
- In
Start(), the numbers (0.6, 1, 0) are measured from the Ship, the flag's parent. - On that line, change
transform.positiontotransform.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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground