Clean Up
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 62 of 67.
Challenge
MediumThe blocks never go away: after a minute of play, 60 of them are falling under the floor, and the script still moves every one. Keep everything from the earlier steps, and change the loop that moves the blocks:
- A block whose y is below -1 is under the floor. Destroy it, and remove it from
blocksso the loop stops moving it.
Press Play, then Check.
Try it yourself
using System.Collections.Generic;
using UnityEngine;
public class Runner : MonoBehaviour
{
[SerializeField] private float speed = 6f;
[SerializeField] private float laneEdge = 4f;
[SerializeField] private GameObject blockPrefab;
[SerializeField] private float spawnEvery = 1f;
[SerializeField] private float fallSpeed = 5f;
private List<GameObject> blocks = new List<GameObject>();
private float timer;
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;
timer += Time.deltaTime;
if (timer >= spawnEvery)
{
timer = 0f;
Vector3 spot = new Vector3(Random.Range(-laneEdge, laneEdge), 10f, 0f);
blocks.Add(Instantiate(blockPrefab, spot, Quaternion.identity));
}
foreach (GameObject block in blocks)
{
block.transform.position += Vector3.down * fallSpeed * Time.deltaTime;
}
}
}
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