- Home /
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() );
}
}
}
I'd suggest that "ball1" isn't a particularly good name for an array. In general, it's a good idea to name your array using the plural version of whatever is stored in each cell. Eg, if each item in your array represents a "ball", your array should probably be called "balls" :-)
Answer by duck · Apr 06, 2010 at 02:56 PM
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++] ); } } }
I'm using javaScript, here is the code:
var ball1 : GameObject[];
var die : int = 6;
function Update () {
if(Input.GetButtonDown("Player3")){
if (ball1.length > 0) { Destroy( ball1[die].Pop() );
}
}
}
And i am getting an error: Pop is not a member of a GameObject.
edited to provide examples of both kinds of array, and explanation of the difference between JS Arrays and built-in arrays.
Your answer
![](https://koobas.hobune.stream/wayback/20220612150103im_/https://answers.unity.com/themes/thub/images/avi.jpg)