As a Tittle, How to Create a list with initial capacity? i make something simple like this
using System.Collection.Generic;
public List<GameObject> ObjectList = new List<GameObject>();
public List<float> ObjectValue;
void Start()
{
GameObject[] something = GameObject.FindGameObjectsWithTag("something");
foreach(GameObject GO in something)
{
ObjectList.Add(GO);
}
ObjectValue = new List<float>(ObjectList.Count);
}
but “ObjectValue” doesnt have any Size/Capacity. i want to make "ObjectValue" size is same with "ObjectList" size.im new in C# and i`m still need learning about that language. Thanks.
5 Answers
5
Like others said you can pass an initial capacity to the constructor of a List, but keep in mind that will only be for the internally used array. To “assign” values to the reserved array slots you still have to use the Add function. Since the capacity equals the size of your other list you can add that much elements without reallocating a new internal array.
ObjectValue = new List<float>(ObjectList.Count);
for (int i = 0; i<ObjectList.Count; i++)
ObjectValue.Add(0f);
Just pass the size you want into the constructor. For 100 element initial size:
public List<GameObject> ObjectList = new List<GameObject>(100);
for (int i = 0; i < T.Count; i++)
ObjectValue.Add(default(T));
Where T is any DataType ie: int, float, etc
My preferred way is to just add an empty array of the correct length using AddRange
public List<GameObject> ObjectList = new List<GameObject>();
public List<float> ObjectValue;
void Start()
{
GameObject[] something = GameObject.FindGameObjectsWithTag("something");
foreach (GameObject GO in something)
{
ObjectList.Add(GO);
}
ObjectValue.AddRange(new float[ObjectList.Count]);
}
can you give me an example script? thanks for fast answer
– m4s4m0r1i think its a static size, but how to make dynamic Size for the List?
– m4s4m0r1Nope, that is not static size. That is the initial size of the list. It will grow if it needs to. The text in the manual for this constructor says: > Initializes a new instance of the > List class that is empty and has > the specified initial capacity.
– robertbuAnd Capacity (which @cdrandin point out) is read and write, so you can also do: public List ObjectList = new List(); ObjectList.Capacity = 100;
– robertbuhmm, thanks. one more question, if i make like this : public GameObject[] justGameObject = new GameObject[10]; i see the size of Array is 10 but when i try this: public List<GameObject> ObjectList = new List<GameObject>(100); i dont see anything (the size is 0).
– m4s4m0r1