Falling Blocks
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 61 of 67.
Challenge
MediumNow blocks fall from the sky. Keep the steering from the last lesson, and add to Runner:
- Three fields the Inspector fills:
blockPrefab(aGameObject: the scene gives it the Block prefab),spawnEvery(1) andfallSpeed(5). - A
List<GameObject>namedblocksthat remembers every block you spawn. - Every
spawnEveryseconds, spawn a Block at a random x between-laneEdgeandlaneEdge, at y = 10 and z = 0, and add it toblocks. - Every frame, move every block in
blocksdown atfallSpeedunits per second.
The blocks cannot hurt the runner yet. Press Play and watch them fall, 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
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon