Menu
CoddyTech

Tower Builder

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

A crane slides back and forth above a base. Each press of Space, or each click, drops a block straight down from the crane. A block that comes down on top of the stack stays there, and the next block has to land on it. A block that misses falls away. The height of the stack is the score.

Write the whole game in one script, Crane, on the crane.

challenge icon

Challenge

Hard

Write the Crane script on the Crane. The Inspector sets blockPrefab (the Block prefab), top (the Base, the top of the stack so far), craneSpeed (3), craneEdge (4) and fallSpeed (7).

  • The crane slides along x at craneSpeed units per second. Past craneEdge it turns back left, and past -craneEdge it turns back right.
  • Space or a left click drops a Block at the crane's x, 1 unit below the crane. While a block is falling, more presses do nothing.
  • The falling block moves down at fallSpeed units per second.
  • When its y gets down to top's y plus 1, and its x is less than 1 from top's x, it lands: set its y to exactly top's y plus 1, make it the new top, and log the height of the stack as Stack: 1, Stack: 2 and so on.
  • A block that does not land keeps falling. Below y = -3, destroy it and log Missed!.

Press Play and build a tower, then Check.

Try it yourself

using UnityEngine;

public class Crane : MonoBehaviour
{
    [SerializeField] private GameObject blockPrefab;
    [SerializeField] private Transform top;
    [SerializeField] private float craneSpeed = 3f;
    [SerializeField] private float craneEdge = 4f;
    [SerializeField] private float fallSpeed = 7f;

    void Update()
    {
    }
}
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