Game Development Reference
In-Depth Information
using
System.Collections.Generic;
A very useful collection class is the
List
class, and we can use it as follows:
List<Snowflake> snowflakes;
As you can see, a
List
declaration expects the
type
between
<
and
>
characters (angled
brackets). This is needed, because
List
needs to know what kind of objects it stores
so that it can reserve enough memory for it (an
Elephant
object is bigger than a
Mouse
object). We have seen the angled brackets before when using the
Content.Load
method which also needs a type to know what kind of asset it should load.
A
List
object is initialized as follows:
snowflakes =
new
List<Snowflake>();
After this initialization,
snowflakes
represents an empty list. We can add objects to
the list as follows:
snowflakes.Add(
new
Snowflake(sprite));
snowflakes.Add(
new
Snowflake(sprite2));
snowflakes.Add(
new
Snowflake(sprite3));
Each item added to the list has its own index, which can be used to access the item.
This is done using brackets (
[
and
]
):
Snowflake first = snowflakes[0];
Snowflake last = snowflakes[2];
Note that the first object in a
List
has index 0, not 1! This is something very easy
to forget and accessing a
List
outside its allowed values will lead to an error (not
a compiler error, but a runtime error; which we will see later on). Another useful
feature of the
List
class is the
Count
property, which counts the number of items
currently in the list:
if
(snowflakes.Count == 0)
dosomething...
Okay, the
List
class seems very useful. So let us now add 500 snowflakes to it:
snowflakes.Add(
new
Snowflake(sprite));
snowflakes.Add(
new
Snowflake(sprite));
snowflakes.Add(
new
Snowflake(sprite));
snowflakes.Add(
new
Snowflake(sprite));
snowflakes.Add(
new
Snowflake(sprite));
snowflakes.Add(
new
Snowflake(sprite));
snowflakes.Add(
new
Snowflake(sprite));
snowflakes.Add(
new
Snowflake(sprite));
snowflakes.Add(
new
Snowflake(sprite));
andsoon...