x


Difference between List<> and Array[]

So I was becoming familiar and comfortable with Arrays, but I recently started using Lists and I'm a little confused about the following code:

private GameObject[] sceneObjects;
sceneObjects = GameObject.FindGameObjectsWithTag ("Clone");

List<GameObject> sceneObjects= new List<GameObject>();
sceneObjects = GameObject.FindGameObjectsWithTag ("Clone");

The first method of adding GameObjects tagged "Clone" to the sceneObjects Array works fine, but it doesn't work with the sceneObjects List.

I thought Lists were very similar to Arrays, so why can't I store my tagged objects the same way?

Thanks!

more ▼

asked Jan 19 '11 at 09:30 PM

ronronmx gravatar image

ronronmx
945 110 121 132

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

2 answers: sort voted first

Lists and built-in arrays are different types, and direct assignment from one to the other isn't supported. However, one of the constructors for List accepts an iterable container as its argument. I'd have to check to be absolutely certain this will work, but I think you should be able to do the following:

var sceneObjects =
    new List<GameObject>(GameObject.FindGameObjectsWithTag("Clone"));

That should have the same end effect that your second code example is intended to have.

more ▼

answered Jan 19 '11 at 09:36 PM

Jesse Anders gravatar image

Jesse Anders
7.6k 8 20 52

alternatively, you can do sceneObjects.AddRange( GameObject.Find.... );

Jan 19 '11 at 09:56 PM Tetrad

Thank you guys, that did the trick ;)

Jan 19 '11 at 10:20 PM ronronmx
(comments are locked)
10|3000 characters needed characters left

The key difference between a list and an array is that an array is fixed size while a list is dynamic -- you can add new elements to a list, but to add a new element to an array you need to create a new larger array and copy the old elements.

Arrays are a little leaner and more efficient if you don't need dynamic resizing, but lists are usually more convenient and the performance difference rarely matters for most applications.

Much more info and opinions here ... http://stackoverflow.com/questions/434761/array-versus-listt-when-to-use-which

more ▼

answered Jan 20 '11 at 07:30 AM

yoyo gravatar image

yoyo
7.7k 29 46 97

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

x1884
x716

asked: Jan 19 '11 at 09:30 PM

Seen: 18119 times

Last Updated: Jan 19 '11 at 09:30 PM