Menu
CoddyTech

Hit!

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

challenge icon

Challenge

Medium

Time for the danger. Keep everything from the earlier steps, and end the game when a block touches the runner:

  • Both are cubes 1 unit wide, so a block touches the runner when their x positions are less than 1 apart and their y positions are less than 1 apart.
  • Check every block after it moves, every frame. On a touch, log Game over and turn the script off with enabled = false, so the runner, the blocks and the spawning all stop.

Press Play and see how long you last, 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;
    [SerializeField] private float fallSpeed = 5f;

    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 = 0f;
            Vector3 spot = new Vector3(Random.Range(-laneEdge, laneEdge), 10f, 0f);
            blocks.Add(Instantiate(blockPrefab, spot, Quaternion.identity));
        }

        for (int i = blocks.Count - 1; i >= 0; i--)
        {
            blocks[i].transform.position += Vector3.down * fallSpeed * Time.deltaTime;
            if (blocks[i].transform.position.y < -1f)
            {
                Destroy(blocks[i]);
                blocks.RemoveAt(i);
            }
        }
    }
}

All lessons in Unity Scripting Basics