Obstacles Ahead
Part of the Building Real Games section of Coddy's Unity journey. Lesson 28 of 56.
Challenge
MediumNow 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
spawnEveryseconds, startingspawnEveryseconds 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 * laneWidthalong x.
Obstacle, with a speed field (the prefab sets 10):
- Every frame, move toward the runner, along -z, at
speedunits 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
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input Swap