x


How do you use RemoveAt or Add with an array of GameObjects?

I get an error ('RemoveAt' is not a member of (UnityEngine.GameObject) if I do this:

var nodes: GameObject[];

var tagName: String; // tag to find objects'

function Start() 

{

    nodes = GameObject.FindGameObjectsWithTag(tagName);

    nodes.RemoveAt(1);

}

What is the syntax to add or remove a GameObject from a array of GameObjects?

This is in Javascript.

more ▼

asked May 10 '10 at 04:01 PM

Zootie gravatar image

Zootie
76 5 6 11

Format code by selecting it and hitting the code button.

May 10 '10 at 04:07 PM Eric5h5
(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

You're getting this error because there are more than one kind of array which you can use in Unity, and they each have different functions and features.

There are built-in arrays, which are fixed-size, and don't have functions which would change their length (like Add, Remove). Built-in arrays are declared using square brackets.

There is also Unity's Javascript Array class, which does have these features - however none of Unity's functions which return collections of objects return Javascript Array objects, they all return built-in arrays!

(there are also many other array-like types available to use, but that's a different topic!)

So if you need to add or remove objects from your collection, generally you would retrieve the built-in array from your unity function, and convert it to a Javascript Array immediately after, like this:

var nodes : Array;
var tagName: String; // tag to find objects

function Start() 
{
    // get fixed array of node objects, store in a temp var:
    var nodesFixedArray = GameObject.FindGameObjectsWithTag(tagName);

    // convert to dynamic array
    nodes = new Array(nodesFixedArray);

    // now we can add/remove!
    nodes.RemoveAt(1);
}
more ▼

answered May 10 '10 at 04:16 PM

duck gravatar image

duck ♦♦
40.9k 92 148 415

Ok, got it. Thank you!

May 10 '10 at 04:29 PM Zootie
(comments are locked)
10|3000 characters needed characters left

That's not possible, but you can convert built-in arrays to dynamic arrays like this:

nodesArray = new Array(nodes);

and back to static arrays like this:

nodes = nodesArray.ToBuiltin(GameObject);
more ▼

answered May 10 '10 at 04:06 PM

Eric5h5 gravatar image

Eric5h5
80.1k 41 132 519

(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:

x1355

asked: May 10 '10 at 04:01 PM

Seen: 5212 times

Last Updated: May 10 '10 at 04:07 PM