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?


more ▼

asked Jan 19, 2011 at 09:30 PM

avatar image

1k 317 236 267

(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, 2011 at 09:36 PM

avatar image

Jesse Anders
7.9k 13 33 67

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

Jan 19, 2011 at 09:56 PM Tetrad

Thank you guys, that did the trick ;)

Jan 19, 2011 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, 2011 at 07:30 AM

avatar image

8.8k 61 179 163

(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



Answers and Comments



asked: Jan 19, 2011 at 09:30 PM

Seen: 21621 times

Last Updated: Jan 19, 2011 at 09:30 PM