- Home /
Check whether all game objects with a tag have been destroyed
I need the game to end once all of the bricks are destoryed. I have already tagged the brick objects in the inspector. I guess im not really sure how to use this for loop properly or something but its not ending my game when all of the bricks are destroyed. Does anyone know how I can fix my code to do that?
var bricks : GameObject[];
function countBricks ()
{
bricks = GameObject.FindGameObjectsWithTag("Player");
for(var i : int = 0; i < bricks.Length; i++)
{
if(i == bricks.Length){
GameOver();
}
}
}
function Start () {
countBricks();
guiScore.text="Score: 0";
}
By the code you provided, the check will be executed once (on start). You should make the check periodical, perhaps move it to the Update() method (although i wouldn't use Find()-like methods in Update).
Find/Finds WithTag is O$$anonymous$$ for an Update - it's the only thing that is.
Answer by whydoidoit · Mar 10, 2014 at 10:43 AM
I guess you need to be checking constantly whether any of the bricks is non-null (has not been destroyed). Perhaps like this:
function Start() {
var bricks = GameObject.FindGameObjectsWithTag("Player");
var brickCount = 0;
do {
yield;
brickCount = 0;
for(var i=0; i < bricks.Length; i++) {
if(bricks[i] != null) brickCount++;
}
} while(brickCount > 0);
GameOver();
}
This checks every frame using a coroutine.
Answer by oliver-jones · Mar 10, 2014 at 10:52 AM
Your while loop in countBricks is only getting called once, at start up.
I would consider calling 'countBricks' every time a brick has been destroyed. So whatever code is destroying the brick, you want to call 'countBricks' from that.
A better way to do this however, would be to have two variables, one that holds the total amount of bricks, and one that holds the destroyed amount of bricks:
var totalBricks : int = 25;
var destroyedBricks : int = 0;
Then, when you're about to destroy your brick, just do:
destroyedBricks += 1;
Within your function Update, you can check:
if(destroyedBricks == totalBricks){
//all bricks have been destroyed
}
Thanks for the reply. This will come in handy as I build my game.
Your answer is the best answer for this question, thank you! ;)
Your answer
![](https://koobas.hobune.stream/wayback/20220613135855im_/https://answers.unity.com/themes/thub/images/avi.jpg)