So, I have a list of vectors, when I put a new vector in it it works perfectly, but If I try to access an index of List of Vectors and put a vector in it, I get this error "Object reference not set to an instance of an object." The code is almost the same for each List:
class GameMap
{
MouseHandler mouseHandler;
TileSet tileSet;
List<Vector2>[] tiles;
List<Vector2> tile;
public GameMap(ContentManager Content)
{
mouseHandler = new MouseHandler();
tileSet = new TileSet(Content);
}
public void Initialize()
{
tiles = new List<Vector2>[tileSet.tiles]; //What am I doing wrong here?
tile = new List<Vector2>();
}
public void MapEditor()
{
mouseHandler.MouseUpdate();
if (mouseH开发者_高级运维andler.LeftButton == true)
{
tiles[0].Add(mouseHandler.MousePosition); //The error comes out here.
tile.Add(mouseHandler.MousePosition);
}
}
public void Draw(SpriteBatch spriteBatch)
{
for (int i = 0; i < tileSet.tiles; i++)
{
tileSet.TiledTexture(spriteBatch, tiles[i], i);
tileSet.TiledTexture(spriteBatch, tile, i);
}
}
}
The "Tiles" with multiples Lists of vectors isn't working, what am I doing wrong?
tiles = new List<Vector2>[tileSet.tiles]
creates a new array of List<Vector2>
with tileSet.tiles
elements. Those elements are null initially. When you access tiles[0].Add(...)
, tiles[0]
is still null
, and thus you get a null reference exception.
You need to do something similar to this:
tiles = new List<Vector2>[tileSet.tiles]
for (int i = 0; i < tiles.Length; ++i)
{
tiles[i] = new List<Vector2>();
}
EDIT:
I guess the point is this:
Although
tile = new List<Vector2>()
and
tiles = new List<Vector2>[tileSet.tiles]
look very similar, they are quite different. The first creates a new List, and the second creates an array of List references, which are initially null. You still have to initialize each of those references to a valid list before you can use it.
tiles[0].Add(mouseHandler.MousePosition);
Although you've created an array to contain a bunch of Lists, You have to instantiate each List in that array.
//something like this:
tiles[0] = new List<Vector2>();
tiles[1] = new List<Vector2>();
...
tiles[n] = new List<Vector2>();
What are you trying to contain with an array of lists? Possibly there is a less nested/complex way to accomplish your goal.
精彩评论