Reputation: 19
I am doing currently a level lock and unlock system with stars.
public class LevelDatas
{
public bool isUnlocked;
public int starsAwarded;
}
[System.Serializable]
public class Levels
{
public List<LevelDatas> levelIndex = new List<LevelDatas>(50);
}
public class LevelManager: MonoBehaviour
{
public Levels level = new Levels();
void Start()
{
}
}
So initially I need to set the list size in the start method. So how can I get this? .........
Upvotes: 0
Views: 8586
Reputation: 90724
A List<T>
has no size!
It has a Count
of how many elements are currently actually added to that list. You can't directly set this. You only can add and remove elements.
And it has a Capacity
for how many elements this list can currently maximal hold without having to re-allocate memory.
For this I need a little excurse.
How does a List work (in simple words)?
By default if you not tell it otherwise a List<T>
has a capacity of 4
. This means you can add up to 4
elements to it without having to think about it.
In the moment you add a 5th element what happens internally is
Capacity
Capacity
4
-> 8
8
elements4
element memory into the new 8
elements memoryCount
from 4
to 5
=> Setting the Capacity
- which is what the constructor List<T>(int)
does
The capacity of a List is the number of elements that the List can hold. As elements are added to a List, the capacity is automatically increased as required by reallocating the internal array.
only makes sense for performance reasons in situations were you already know that you need at least a certain amount of elements anyway.
So there are now basically two options for your question depending on your needs
If you want a fixed size of elements rather use an array!
[SerializeField] private LevelData[] levelIndex = new Leveldata[50];
Note though - since you make your field serialized - that via the Inspector in Unity you can still change that default array's size so the Inspector will automatically allocate a new array with according changed size.
If you still want a dynamic list where you can add and remove entries on runtime but you want it to initially hold 50 elements you could initiliaize it via an array once like
[SerializeField] private List<LevelData> levelIndex = new List<Leveldata>(new Leveldata[50]);
This now uses the other constructor List<T>(IEnuemrable<T>)
which actually adds all the elements of the array to the list as elements.
Again in case you expose this in the Inspector this would only be the default state for that field. You could still add and remove entries via the Inspector the same way as for the array.
Upvotes: 3