Perform a Task when Objects are Destroyed

So i have some targets (there are three types, easy medium and hard each type with its own tag) and a cannon that shoots a ball. When i hit the targets they are destroyed and i receive a certain amount of points depending on the target. I want to be able to load a gui button when all targets are destroyed. How could i do this.

You could also make sure you have all targets in the same empty gameobject (child them on instantiation) and use Transform.childCount. Preferably count the childs right before you destroy a target. This way is always failsafe as it’ll always return the correct quantity of existing targets (Wolfram’s answer will of course work as well, just make sure that you always keep the numbers straight).

Another way is to use a for-loop and find the objects by name (which is eating more CPU, so make sure this method doesn’t run to frequently), this is particularly good if you won’t be able to track the number from the start for some reason.

Way simpler then all of these is to have a counter in the script handling your GUI. If the counter is equal to the number of targets, display the gui. To increment the counter attach to each target

OnDestroy () {
//increment counter
}

You should create a var tracking the number of targets, for example in the script that creates your targets. Initialize it to the total number of targets you create. In the Update function, enable the gui button if the number reaches 0.

Then, each time the ball hits a target, subtract 1 from that number, for example in its OnCollisionEnter() function.

Use these two scripts:

Place this on the target:

var pointsGiven : float = 10; //Your points here
var targetCounter : GameObject;

function OnCollisionEnter (thing : Collision) {
	var targetCounterScript = targetCounter.GetComponent("TargetCounter");

	if(thing.gameObject.tag == "Cannonball"){
		targetCounterScript.targets -= 1; //subtract targets
		targetCounterScript.score += pointsGiven; //add score
		Destroy(thing.gameObject); //destroys the cannonball
		Destroy(gameObject); //destroys target
	}
}

And place this on your score GUI. IMPORTANT: make sure to name this script TargetCounter.

var targets : int = 10;
var score : float = 0;

function Update () {
	
	if(targets <= 0){
		//button logic
	}

	guiText.text = "Score " + score.ToString("f0"); //update score every frame
}

Add the “Cannonball” tag to the cannonballs. For the button logic part, just have your GUI button turn its button script on.