My solution to count blocks in level

I wanted to do something with lists, and also I didn’t want to work on 2 classes to find the number of blocks.
So at the Start method I add to the list all the blocks in the level, and in the CountBlocksInLevel method I did a for loop that goes over all the items in the list. If soemthing gets destroied in the level I remove it from the list, and if there are no items in the list I move to the new scene

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class LevelCheck : MonoBehaviour
{
    [SerializeField] List<Block> blocks = new List<Block>();
    [SerializeField] Object nextScene;

    private void Start()
    {
        blocks.AddRange(FindObjectsOfType<Block>());
    }

    private void Update()
    {
        CountBlocksInLevel();
    }

    private void CountBlocksInLevel()
    {
        for (int i = 0; i < blocks.Count; i++)
        {
            if (!blocks[i])
            {
                blocks.RemoveAt(i);
            }
            if(blocks.Count == 0)
            {
                SceneManager.LoadScene(nextScene.name);
            }
        }
    }
}
4 Likes

Smart solution

4 Likes

Privacy & Terms