Menu
CoddyTech

Blocks from the Sky

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

challenge icon

Challenge

Medium

Spawn a block in the sky every second. Keep the steering.

  1. Add [SerializeField] private GameObject blockPrefab;, [SerializeField] private float spawnEvery = 1f; and private List<GameObject> blocks = new List<GameObject>();.
  2. Add Time.deltaTime to a float timer; when it reaches spawnEvery, take spawnEvery off it.
  3. Then spawn a block at new Vector3(Random.Range(-laneEdge, laneEdge), 10f, 0f) and add it to blocks.

Press Play: blocks appear high above the lane. Then Check.

Try it yourself

using UnityEngine;

public class Runner : MonoBehaviour
{
    [SerializeField] private float speed = 6f;
    [SerializeField] private float laneEdge = 4f;

    void Update()
    {
        Vector3 p = transform.position;
        p.x += Input.GetAxisRaw("Horizontal") * speed * Time.deltaTime;
        p.x = Mathf.Clamp(p.x, -laneEdge, laneEdge);
        transform.position = p;
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground