Menu
CoddyTech

Falling Blocks

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

challenge icon

Challenge

Medium

Now blocks fall from the sky. Keep the steering from the last lesson, and add to Runner:

  • Three fields the Inspector fills: blockPrefab (a GameObject: the scene gives it the Block prefab), spawnEvery (1) and fallSpeed (5).
  • A List<GameObject> named blocks that remembers every block you spawn.
  • Every spawnEvery seconds, spawn a Block at a random x between -laneEdge and laneEdge, at y = 10 and z = 0, and add it to blocks.
  • Every frame, move every block in blocks down at fallSpeed units per second.

The blocks cannot hurt the runner yet. Press Play and watch them fall, then Check.

Try it yourself

using UnityEngine;

public class Runner : MonoBehaviour
{
    [SerializeField] private float speed = 6f;
    [SerializeField] private float laneEdge = 4f;

    void Update()
    {
        Vector3 p = transform.position;
        p.x += Input.GetAxisRaw("Horizontal") * speed * Time.deltaTime;
        p.x = Mathf.Clamp(p.x, -laneEdge, laneEdge);
        transform.position = p;
    }
}

All lessons in Unity Scripting Basics