|
-
April 18th, 2009, 01:27 PM
#1
'System.NullReferenceException when using an array
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
Code:
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
Code:
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?
-
April 18th, 2009, 05:15 PM
#2
Re: 'System.NullReferenceException when using an array
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:
Code:
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;
}
Last edited by BigEd781; April 18th, 2009 at 05:18 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|