Foreach loop with 2d array of objects

Posted by Jacob Millward on Game Development See other posts from Game Development or by Jacob Millward
Published on 2012-11-03T11:34:13Z Indexed on 2012/11/03 17:23 UTC
Read the original article Hit count: 310

Filed under:
|
|

I'm using a 2D array of objects to store data about tiles, or "blocks" in my gameworld. I initialise the array, fill it with data and then attempt to invoke the draw method of each object.

foreach (Block block in blockList)
  {
    block.Draw(spriteBatch);
  }

I end up with an exception being thrown "Object reference is not set to an instance of an object".

What have I done wrong?

EDIT: This is the code used to define the array

Block[,] blockList;

Then

blockList = new Block[screenRectangle.Width, screenRectangle.Height];
  // Fill with dummy data
  for (int x = 0; x <= screenRectangle.Width / texture.Width; x++)
  {
    for (int y = 0; y <= screenRectangle.Height / texture.Width; y++)
    {
      if (y >= screenRectangle.Height / (texture.Width*2))
      {
        blockList[x, y] = new Block(1, new Rectangle(x * 16, y * 16, texture.Width, texture.Height), texture);
      }
      else
      {
        blockList[x, y] = new Block(0, new Rectangle(x * 16, y * 16, texture.Width, texture.Height), texture);
      }
    }
  }

© Game Development or respective owner

Related posts about XNA

Related posts about c#