My Solution to keeping track of blocks

I serialize the parent object of the blocks in the level, then count the number of children.
In my Update() i make sure the number of blocks is greater than 0, and if its not then the game is won.
The extra code is for player feedback.

Here is my code:

[SerializeField] Ball ball;
[SerializeField] Paddle paddle;
[SerializeField] GameObject WinScreen;
[SerializeField] TextMeshProUGUI blocksRemaining;
[SerializeField] GameObject blocks;
Block[] children;
int remainingBlocks;
// Start is called before the first frame update
void Start()
{
    UpdateBlocks();
}

// Update is called once per frame
void Update()
{
    if(remainingBlocks > 0)
    {
        UpdateBlocks();
    }
    else
    {
        // The game is won
        WinScreen.SetActive(true);
        ball.gameObject.SetActive(false);
        paddle.gameObject.SetActive(false);
    }
}

void UpdateBlocks()
{
    children = blocks.GetComponentsInChildren<Block>();
    remainingBlocks = children.Length;
    blocksRemaining.text = remainingBlocks.ToString();
}

Privacy & Terms