Hey there, Gamers and Game Makers!
In this week's blog, we're going to continue with our introduction to C# series by looking at Arrays. Let's get started.
So what exactly is an Array? Well, you can think of an Array as a type of variable but an Array contains essentially a list of information. So for example if you have an int Array then that Array will contain multiple int values.
We declare an Array in the following way:
You first declare the type of Array you want by declaring the variable type as normal. You then follow that with a pair of square brackets.We then follow this with the name you want to give your Array followed by an equals sign and then "new" followed by the variable type. Finally we finish with another pair of square brackets. This time however, we put the size of our Array inside these brackets. This defines how many places are in our Array.
I'm going to create an Array called names. So it'll look as follows:
Ok, so how do we go about adding values to the positions of our new Array? We can simply say the name of our Array followed by square brackets with the index position of our Array followed by an equals sign and finally followed by the new value. Keep in mind that an Array starts its index position at 0. So the first value of your Array will be at position 0.
If I want to add my name to the first position of the Array of names, it'll look as follows:
Ok, I'm going to assign values to the other positions of our Array so that it is full. Our script currently looks as follows:
Now that our Array is full, let's try printing the values from various positions in the Array. So if I want to print the name held at index position two, I'd type the following:
As you can see, when we run the script, the name John is printed out. This is because we are telling our script to print the name held at index position two. If you look at your initialization, you see that index position two is given the string value of "John" and that is what get's printed to the console.
If I change the index position to one, we see the name "Tim" being printed because that is the name held at that index position.
That does it for this quick introduction to Arrays. We can do so much more with Arrays so I encourage you to play around with them.
Until next time!