How to organize arrays in unity3d?

When we declare a dynamic array of gameobjects. If a game object is removed from the scene the empty slot of the removed object will still remain in the array.

let's say this is our array:

var objects:Array = new Array();

and objects has gameobjects added as below:

objects[0] = go1;
objects[1] = go2;
objects[2] = go3;

if I destroy objects[1] ,then whenever accessing objects[1] it'll return null. My question is when you have a quite large array what is the efficient way of dragging out the empty slots from the array without having to go through large loops?

Cause the loop method then needs you to have a temp array to store the non-null values which it means using more memory.

You should probably use a Generic list for starters. It's type safe and has more built-in functionality than Unity's array class (which is basically a wrapper around ArrayList)

If you insist on using the Array Class, then you can use Remove() and give the index of the object you want to remove from the array.


But if you use a List, then you can use Remove() and either pass the object index or the reference to the object and it will remove it as well.


Both classes also have a Sort() method that will let you rearrange the array when you want to.