Is this solution OK?

It works. My question is: should I just think “if it works, it’s good”, or is there an underlying threat to my solution (for example, in a future scenario)?

Solution:

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

public class Level : MonoBehaviour
{

int numberBlocks;

private void Awake()
{
    GameObject blocks = new GameObject("Blocks");
}

// Start is called before the first frame update
void Start()
{
    countBlocks();
    //Debug.Log(blocks.name + " has " + blocks.transform.childCount + " children");
}

private void countBlocks()
{
    GameObject blocks = GameObject.Find("Blocks");
    numberBlocks = blocks.transform.childCount;
}

// Update is called once per frame
void Update()
{
    countBlocks();
    Debug.Log(numberBlocks + " blocks left");
    if (numberBlocks == 0)
    {
        SceneManager.LoadScene("Win");
    }
}

}

Hi Martin,

Generally, this is what you should do because you are no clairvoyant. Don’t worry about problems that you do not have.

In larger games, you’ll probably notice a negative impact on the performance because Unity’s Find methods are very slow and expensive. They should not be called each frame. In a little game like ours, it does not matter, though.

If you would like to optimise your code and check the number of blocks each frame, you could do this:

GameObjects[] blocks = null;

void Start()
{
    blocks = GameObject.Find("Blocks");
    //Debug.Log(blocks.name + " has " + blocks.transform.childCount + " children");
}

private int GetNumberOfBlocks()
{
    if (blocks == null) { return 0; }
    
    int n = 0;

    foreach (GameObject block in blocks)
    {
        if (block != null) { n++; }
    }

    return n;
}

// Update is called once per frame
void Update()
{
    int numberOfBlocks = GetNumberOfBlocks();

    if (numberOfBlocks == 0)
    {
        SceneManager.LoadScene("Win");
    }
}

The foreach loop checks the array of the blocks that were found in Start(). When a block gets destroyed, it does not exist anymore. The reference becomes null. Doing this is way more performant to do this than to call the Find method each frame. Not perfect but more performant.

Did this help?

1 Like

Thanks @Nina ! This makes sense a lot.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms