Menu
CoddyTech

Crossing the Road

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

A hopper waits at the edge of a busy road. Cars come in from the left in three lanes and drive across. The player hops forward or back one lane at a time with the up and down arrows, and has to time each hop to reach the far side. A car that touches the hopper sends it back to where it started.

Write the whole game in one script, Crossing, on the hopper.

challenge icon

Challenge

Hard

Write the Crossing script on the Hopper, which starts at z = -4, below a road with three lanes. The Inspector sets carPrefab (the Car prefab), lanes (the lanes' z positions: -2, 0 and 2), spawnEvery (1) and carSpeed (5).

  • Each press of the up arrow hops the hopper 2 units forward (+z). Each press of the down arrow hops it 2 units back, but never behind where it started.
  • Every spawnEvery seconds, a Car appears at x = -9, y = 0.5, in a random lane from lanes. Cars drive along +x at carSpeed units per second, and a car whose x is above 9 is destroyed.
  • A car hits the hopper when their x positions are less than 1.5 apart and their z positions less than 1 apart. A hit logs Hit! and puts the hopper back where it started.
  • When the hopper reaches z = 4, the far side, log You made it! and turn the script off.

Press Play and cross the road, then Check.

Try it yourself

using System.Collections.Generic;
using UnityEngine;

public class Crossing : MonoBehaviour
{
    [SerializeField] private GameObject carPrefab;
    [SerializeField] private float[] lanes;
    [SerializeField] private float spawnEvery = 1f;
    [SerializeField] private float carSpeed = 5f;

    void Start()
    {
    }

    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