Add an object to Array

hi i want to know how i can add an gameobject to a Array when the gameObject is created i want to have a command that add the object to a spesific array in another Script file

and if the gameObject is Desroyed remove him from the Array and fix the Array what i mean is if the Array has 5 entrys and entry 3 is Desroyed i want entry 4 to be 3 and 5 to be 4

sorry for my bad spelling :S and im Writing this in JavaScript

There is no “Add” method on the builtin array type! The above will not compile, even if you do use “GameObject” instead of “gameObject”.

However, try this:

var array1 : GameObject[];

function addToArray (obj : GameObject) {
   array1 += [obj];
}

Voila! Note that this is less efficient than implementations such as a fixed-maxsize array with an end cursor, but I tend to use it when the adding to the array is not performance-critical (eg. bullet is created), thus making it easy to use these fast builtin arrays, so that the performance critical array-READING code (eg. for every bullet every frame, check for hits).

You can pretty easily go about adding and subtracting from an array, here's an example

//this is the array you will be modifying, you will need to get a hold of it first if it is in another script
var array1 : gameObject[];

// this function will need to have the object that is being added passed in to it.    
function addToArray (obj : gameObject) {
   array1.Add(obj)
}

And as far as subtracting a gameObject goes you could try removing it from the array before you destroy it.

// this function will need to have the object that is being removed passed in to it.
function destroyObject (obj : gameObject) {
    var objectIndex : int;
    // find the index of the object to be deleted (what number it is in the array)
    for (var i : int=0 ;i<array1.length; i++){
        if(array1[1] == obj)
            objectIndex = i;
    }
    //remove the object from the array
    array1.RemoveAt(objectIndex);
    //now destroy it
    Destroy(obj);
}