Menu
CoddyTech

Obstacles Ahead

Part of the Building Real Games section of Coddy's Unity journey. Lesson 28 of 56.

challenge icon

Challenge

Medium

Now the obstacles. The scene has an Obstacle prefab, a red block with a trigger collider and your Obstacle script, and the Spawner object stands at the far end of the road, at (0, 0.75, 40). Keep the runner from the last lesson, and fill in two scripts.

Spawner, with fields the Inspector sets: obstaclePrefab, spawnEvery (1.2) and laneWidth (2.5):

  • Every spawnEvery seconds, starting spawnEvery seconds after Play, make an obstacle from the prefab.
  • Pick its lane at random from -1, 0 and 1, and put it at the Spawner's position moved lane * laneWidth along x.

Obstacle, with a speed field (the prefab sets 10):

  • Every frame, move toward the runner, along -z, at speed units per second.
  • Once its z is below -10, behind the camera, destroy it.

The obstacles pass through the runner for now: the crash comes in a later lesson. Press Play and watch them come, then Check.

Try it yourself

using UnityEngine;

public class Spawner : MonoBehaviour
{
    // Sends obstacles down the road. The next lesson fills this in.
}

All lessons in Building Real Games