- Home /
Question by
Lockstep · Mar 03, 2013 at 02:36 AM ·
destroyresizeexecuteineditmode
Destroy gameObject when array is resized.
Hi. I'm working on a waypoint system. I want to add and remove waypoints dynamically in the editor using an array. Creating new points is quite easy using:
if(list[i] == null) list[i] = new GameObject().transform;
When increasing the size of my array, the new transforms will pop up as intended. But I also want them to disapear when I decrease the size of the array.
Question: How can I dynamically destroy gameObjects when they are thrown out of an array due to me manually resizing it?
Comment
Best Answer
Answer by Lockstep · Mar 03, 2013 at 11:02 AM
Problem solved! Now I use a second array which keeps track of my transforms after resizing. Here is the essence of my code:
//Create new handles and make sure they are individuals
for(int i = 0; i < list.Length; i++){
if(list[i] == null ) list[i] = new GameObject().transform;
for (int j = 0; j <i ; j++){
if(list[j] == list[i]) list[i] = new GameObject().transform;
}
}
//Destroy any unused handle
if(listCopy == null) listCopy = new Transform[0];
//Debug.Log("List.length: " + list.Length + " listCopy.Length: " + listCopy.Length);
if(list.Length != listCopy.Length){
//Debug.Log(" != ");
if(list.Length < listCopy.Length){
//Debug.Log("Destroying");
int dif = listCopy.Length - list.Length;
for (int i = listCopy.Length - 1; i > listCopy.Length - 1 - dif; i--){
DestroyImmediate(listCopy[i].gameObject);
}
}
listCopy = list;
}