Sunday 26 February 2017

c# - Object reference not set to an instance of an object, generating win forms control via code

I'm making a simple space invaders type game for my class and I'm trying to generate everything through my code. I have 3 methods causing me a problem




private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
GenerateBullet();
}
private void GenerateBullet()
{
playerBullet = new PictureBox()
{
Parent = backBoard,

Size = new Size(4, 12),
Visible = true,
Enabled = true,
Image = Properties.Resources.Untitled,
SizeMode = PictureBoxSizeMode.StretchImage
};
}
private void BulletMovement(object sender, EventArgs e)
{
if (playerBullet.Enabled == true)

{
playerBullet.Top += 4;
}
}


The 3rd method that checks the enabled and moves based on that is what is throwing the error 'Object reference not set to an instance of an object.' . Is there a way to fix this without actually generating the picture through the toolbox/form design.



The BulletMovement is called by a timer tick sorry that I didn’t make that clear

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...