Menu
CoddyTech

Let Them Fall

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

challenge icon

Challenge

Medium

Make every block in the list fall. Keep everything from the earlier steps.

  1. Add [SerializeField] private float fallSpeed = 5f;.
  2. At the end of Update(), loop with foreach (GameObject block in blocks).
  3. In it, add Vector3.down * fallSpeed * Time.deltaTime to block.transform.position.

Press Play: the blocks rain down past the runner. Then Check.

Try it yourself

using System.Collections.Generic;
using UnityEngine;

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

    private List<GameObject> blocks = new List<GameObject>();
    private float timer;

    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;

        timer += Time.deltaTime;
        if (timer >= spawnEvery)
        {
            timer -= spawnEvery;
            Vector3 spot = new Vector3(Random.Range(-laneEdge, laneEdge), 10f, 0f);
            blocks.Add(Instantiate(blockPrefab, spot, Quaternion.identity));
        }
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground