Menu
CoddyTech

Hoist the Flag

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

localPosition can be read and changed on every frame, like position. A child that should climb its parent, a cabin up a tower or a flag up a mast, moves along localPosition and compares its local height with the top, so it works wherever the parent stands:

if (transform.localPosition.y < 10)
{
    transform.localPosition += new Vector3(0, 2 * Time.deltaTime, 0);
}

Compared with position.y instead, the top would move whenever the parent stands higher or lower.

challenge icon

Challenge

Medium

Hoist the flag up the mast with the up arrow.

  1. In Update(), write if (Input.GetKey(KeyCode.UpArrow) && transform.localPosition.y < 4).
  2. Inside it, add new Vector3(0, climb * Time.deltaTime, 0) to transform.localPosition.

Press Play and hold the up arrow: the flag climbs to the top of the mast and stops. Then Check.

Try it yourself

using UnityEngine;

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

    void Start()
    {
        transform.localPosition = 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