Source file unity-csharp/arcade-classics/frogger/Lane.cs from the GDnD code examples. Download raw file
// GDnD wiki example
// Demonstrates: timer-driven spawning of moving hazards from one screen edge, per lane
// Related pages: [[overview-arcade-classics-as-learning-projects]], [[monobehaviour-lifecycle]]
using UnityEngine;
// A single horizontal lane. On a timer it spawns one hazard at the entry edge and
// launches it across at the lane's speed. The sign of the speed decides the
// direction (and therefore which edge it enters from). Safe lanes spawn nothing.
// The game adds and configures these at runtime.
public class Lane : MonoBehaviour
{
private FroggerGame.LaneType type;
private float speed;
private float spawnInterval;
private Hazard hazardPrefab;
private float laneY;
private float spawnTimer;
private Camera cachedCamera;
public void Configure(FroggerGame.LaneType laneType, float laneSpeed, float interval, Hazard prefab, float y)
{
type = laneType;
speed = laneSpeed;
spawnInterval = interval;
hazardPrefab = prefab;
laneY = y;
cachedCamera = Camera.main;
// Stagger the first spawn so lanes do not all fire on the same frame.
spawnTimer = Random.Range(0f, Mathf.Max(0.01f, spawnInterval));
}
private void Update()
{
if (hazardPrefab == null || spawnInterval <= 0f)
{
return;
}
spawnTimer += Time.deltaTime;
if (spawnTimer >= spawnInterval)
{
spawnTimer -= spawnInterval;
Spawn();
}
}
private void Spawn()
{
float halfWidth = cachedCamera.orthographicSize * cachedCamera.aspect;
float entryX = speed >= 0f ? -halfWidth - 1f : halfWidth + 1f;
Hazard hazard = Instantiate(hazardPrefab, new Vector3(entryX, laneY, 0f), Quaternion.identity, transform);
hazard.Launch(new Vector2(speed, 0f));
}
}