Menu
CoddyTech

Road Traffic

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

challenge icon

Challenge

Hard

Send cars down the road.

  1. Every spawnEvery seconds, spawn a car at (-9, 0.5, lanes[Random.Range(0, lanes.Length)]) into a list.
  2. Move each car along +x at carSpeed; past x = 9, destroy and remove it.
  3. A car under 1.5 away on x and 1 on z logs Hit! and sends the hopper back to start.

Press Play: cars stream by. 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;

    private Vector3 start;

    void Start()
    {
        start = transform.position;
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            transform.position += new Vector3(0f, 0f, 2f);
        }
        if (Input.GetKeyDown(KeyCode.DownArrow) && transform.position.z > start.z)
        {
            transform.position -= new Vector3(0f, 0f, 2f);
        }
        if (transform.position.z >= 4f)
        {
            Debug.Log("You made it!");
            enabled = false;
            return;
        }

        // Cars: the next lesson.
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground