x


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

more ▼

asked Mar 19 '10 at 05:38 PM

Rufalo gravatar image

Rufalo
65 5 6 13

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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);
}
more ▼

answered Mar 19 '10 at 08:45 PM

Jason_DB gravatar image

Jason_DB
1.9k 4 14 36

should probably be:

if(array1[i] == obj)

Jun 01 '12 at 07:04 PM gl03
(comments are locked)
10|3000 characters needed characters left

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).

more ▼

answered Jun 21 '11 at 11:26 AM

Waz gravatar image

Waz
6.4k 22 33 70

(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x3451
x353

asked: Mar 19 '10 at 05:38 PM

Seen: 3345 times

Last Updated: Jun 01 '12 at 07:04 PM