Menu
CoddyTech

Crossing the Road

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

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

Start the road crossing game: the hopper hops lane by lane.

  1. In Start(), save transform.position in a Vector3 start field.
  2. Each press of the up arrow hops 2 units along +z. The down arrow hops 2 back, only while z is above start.z.
  3. When z reaches 4, log You made it! and set enabled = false.

Press Play and hop to the far side. 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()
    {
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground