Menu
CoddyTech

Clean Up

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

Taking items out of a list while a foreach walks it stops the script with an InvalidOperationException. Loop backwards with for instead: removing item i moves only the items after it, which the loop has already visited.

for (int i = coins.Count - 1; i >= 0; i--)
{
    if (coins[i].transform.position.y > 20f)
    {
        Destroy(coins[i]);
        coins.RemoveAt(i);
    }
}
challenge icon

Challenge

Medium

Clear away the blocks that fall under the floor.

  1. Replace the foreach with for (int i = blocks.Count - 1; i >= 0; i--), moving blocks[i] down as before.
  2. After the move, when blocks[i].transform.position.y < -1f, call Destroy(blocks[i]); and then blocks.RemoveAt(i);.

Press Play: the Hierarchy never holds more than a few blocks. 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 -= spawnEvery;
            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

Practice on your own: Unity playground