Click to See Complete Forum and Search --> : 'System.NullReferenceException when using an array


maitopoika
April 18th, 2009, 01:27 PM
I am greating an Array on UFO type (just a class i created)
When I try instantiate any. or all for that matter, of the elements in the array I get the following
error
An unhandled exception of type 'System.NullReferenceException' occurred in spaceInvaders.exe

Additional information: Object reference not set to an instance of an object.
and points to this line in th code
item.X = screen.Height / 2;

here is the code for that part


public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Viewport screen;


//create background image
Texture2D background;
Rectangle mainFrame;

UFO[] aliensArr = new UFO[5];

protected override void Initialize()
{
screen = graphics.GraphicsDevice.Viewport;

foreach (UFO item in aliensArr)
{

item.X = screen.Height / 2;
item.Y = screen.Width / 2;
item.Width = 75.0f;
item.Height = 50.0f;
}
base.Initialize();
}
......
}


and the UFO class is

class UFO
{
public Texture2D Visual { get; set; }
public float X { get; set; }
public float Y { get; set; }
public float Width { get; set; }
public float Height { get; set; }
public Rectangle Rect
{
get
{
return new Rectangle((int)X, (int)Y, (int)Width, (int)Height);
}

}

}


any ideas why i am getting this?

BigEd781
April 18th, 2009, 05:15 PM
Simply creating the array does not construct the objects. Creating the array reserves space for the objects of type 'UFO', but they are not initialized. You need to create the UFO objects first by calling the constructor for each element. So your code needs one more line:


for (int i = 0; i < aliensArr.Length; ++i)
{
aliensArr[i] = new UFO();
aliensArr[i].X = screen.Height / 2;
aliensArr[i].Y = screen.Width / 2;
aliensArr[i].Width = 75.0f;
aliensArr[i].Height = 50.0f;
}