- Home /
How to remove objects from an array and destroy
Hi! This is my first question but probably not the last. What I was trying to accomplish with this is to remove the gameobject from the array and destroy it when it collides with a specific object.
The commented line (global.arr.RemoveAt[i];) is currently giving an error as follows: Type 'function(int): void' does not support slicing.
Which makes my head explode. I'm very noob. Is my loop wrong somehow? Is it syntax? Wrong array type for what I'm doing? I'm also not sure that comparing the position is the best way to verify I have the right object from the list. Any help is greatly appreciated!
function OnCollisionEnter(theCollided : Collision){ //when an object collides with something named ground if(theCollided.gameObject.name == "ground"){ //set a variable to the number of entries in the array -1 to get last array entry var ii : int = global.arr.length -1; //loop through the array for(i=ii; i>=0; i--){ //if the object on the list has the same position as the collided... if(global.arr[i].transform.position == gameObject.transform.position){ //remove the object from the list // global.arr.RemoveAt[i]; //print the new list for verification Debug.Log(global.arr); //destroy the object Destroy(gameObject); } }
}
}
Answer by Peter G · Jan 16, 2011 at 05:29 PM
Without knowing what global.arr is besides an array, the only problem I see is that your are trying to use an indexer to pass an argument to a function. You should do:
global.arr.RemoveAt(i);
I also don't think that you are destroying the right GameObject. gameobject
is the object that the script is attached to. It sounds like you want to destroy the other object in which case you want to do:
//inside your for loop
var deadGB = global.arr[i];
global.arr.RemoveAt(i);
Destroy(deadGB);
Wow! Seems like I wasted so much time. Thank you for your quick and helpful response!