Road Traffic
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 83 of 85.
Challenge
HardSend cars down the road.
- Every
spawnEveryseconds, spawn a car at(-9, 0.5, lanes[Random.Range(0, lanes.Length)])into a list. - Move each car along +x at
carSpeed; past x =9, destroy and remove it. - A car under
1.5away on x and1on z logsHit!and sends the hopper back tostart.
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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground