Destroying objects one at a time

How do i destroy an array of objects one at a time when using an input key?

Here's the code so you can see it better:

var ball1 : GameObject[];

var die : int = 6;

function Update () {

if(Input.GetButtonDown("Player1")){

if (ball1.length > 0) {
            Destroy( ball1[die].Pop() );

}

}

}

The answer to this question will vary depending on whether you're using a built-in array, or a Javascript Array.

(If you define your array using `Array()`, it's a Javascript array. If you define your array using square brackets, it's a built-in array - even if you're using Javascript!).

This version is for Javascript arrays, and uses the 'Pop' method to remove & return the last item in the array, which is then used by Destroy() to destroy that object:

// Javascript array version:
function Update() {
    if (Input.GetKeyDown(KeyCode.D)) {
        if (objectsToDestroy.length > 0) {
            // Remove & destroy last element in array
            Destroy( objectsToDestroy.Pop() );
        }
    }
}

This version is for built-in arrays, which have a fixed-size at runtime, so you can't simply shrink the array by removing items from it, and doesn't have the Pop function, so instead we create an index counter variable which determines the next item to be destroyed:

// Built-In array version:
var objectsToDestroy : GameObject[];
private var nextIndexToDestroy : int = 0;

function Update () {
    if(Input.GetButtonDown(KeyCode.D)){
        if (nextIndexToDestroy < objectsToDestroy.length) {
            // destroy current object, and increment counter:
            Destroy( objectsToDestroy[nextIndexToDestroy++] );
        }
    }
}