- Home /
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!
Answer by Jesse Anders · Jan 19, 2011 at 09:36 PM
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.
alternatively, you can do sceneObjects.AddRange( GameObject.Find.... );
Answer by yoyo · Jan 20, 2011 at 07:30 AM
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