Now we talk about List<>.
First of all, what is the difference between Array and List?
At pure logic level, there are few difference, even the syntax is 90% the same.
The big diffrence is this :
ARRAYS ARE STATIC, LISTS ARE DYNAMIC.
What it means?
In easy word, with LIST<> we can increase or decrease the number of elements inside it at RUN TIME.
Lists have special methods to add or remove something directly when Game runs.
With the Arrays “technically” you can do it, but is a waste of memory, because to add or remove object inside it, we have to RECREATE ANOTHER ARRAY, and COPY FROM ONE TO ANOTHER EVERY SINGLE ELEMENT.
With the List, all of this can be executed by default methods inside List class.
Array are IMPORTANT but most of time we will use List<>.
Look at the syntax
Same as Arrays, can be public or private with [SerializeField] attribute
The keyword is List<>, inside <here> we need to put the TYPE of elements we want into collection.
We have numbers, so INT VALUE, and the name of our Collection (numbers).
With this syntax we DECLARE al List, but it is not inizialize yet.
To do that
We can INITIALIZE IT DIRECTLY in Start after we DECLARE it, or we can make both at the same time
As the Arrays, we can add the elements inside List at the Initialization
As we can see, Array and List are really similar.
The Foreach loop works EXACTLY THE SAME WAY for Lists and Arrays.
This is the C# Microsoft documentation for the Lists<>
As you can see, I’m not going to deep in this topic, I simply give you little tips to understand what and when we can use the Collections.
I prefer give you the documentation, and with that you can search what we need.
This is beacuse I prefer finish our Shooter 2D project.
After we finish it, I will write a little bit deeper about C# language.
There are many incredible feature, and we need to talk about it more to understand better.
For now this is a simply “guideline” with basic information, but at the same time we can learn togheter how work the flow of code!
But in any case, every time we have to use Collection or something specific, I will try to explain step by step what I’m doing and why.
And the best part is that my way of solving problems is MY WAY, not the RIGHT WAY!
Remember: there is no wrong way, there is probably a better way to solve the problem, but if it works, you are still processing the logic, and that’s fine!
Just for sake of knowledge, in the next article I will talk about some of the most used methods for Arrays and Lists.