How do I check if all the objects are destroyed then end the game?

Hey guys, so I’m working on a game that the player needs to destroy all the boxes in the map by jumping on them and reach the end. I want the end block check and see if all the boxes are destroyed (Deactivated) then print something like “you won!” on the screen and give the player the option to press enter to try the same level again or press X to continue to next level. I only want the part that checks if all the boxes are gone. I know I have to use a For loop but I’m not quite sure how I’m supposed to script it since I’m fairly new to this.
Here is where this script should go I believe:

var text : GUIText;

var colliding : boolean;

private var displayText : String = “”;

function Update()
{
    if (colliding)
    {
       text.enabled = true;
    }
    else
    {
       text.enabled = false;
    }
}

function OnTriggerEnter(col : Collider)
{
    if (col.gameObject.CompareTag("Player"))
    {
       colliding = true;
       displayText = "You Won!";
       Application.LoadLevel(Application.loadedLevel);

    }
}

function OnGUI()
{
    GUI.Box(Rect((Screen.width / 2) - 70, 10, 140, 40), displayText);
}`

Thanks.

I think the simplest way to check if any boxes remain:

if (GameObject.FindWithTag("Box") == null) {
    //level complete
}

This has a small efficiency advantage over FindGameObjectsWithTag in that it returns a single object rather than assembling a collection of objects.

However this code is unsuitable to attach to a Box. When the last remaining box calls FindWithTag() it will return that box and result in the condition returning False .


If the script is being attached to a box then this is more suitable:

if (GameObject.FindGameObjectsWithTag("Box").Length == 1) {
    //level complete
}

The most efficient way would be to start with a count of the number of boxes and decrement a number each time one is destroyed. If all the boxes share a tag, then you can use this less efficient alternative:

var boxes = GameObject.FindGameObjectsWithTag("Box");
if (boxes.Length == 0) {
    Debug.Log("All the boxes are gone");
}

Other than the count method, most other methods involve either keeping a list of the boxes or finding a list of the boxes.