-1

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

Velarux
  • 9
  • 5
  • There are pieces missing from your code. It is not clear when your “BulletMovement” method is triggered. Plz share the same and also the sequence in which all the methods are triggered. – dj079 Nov 10 '18 at 08:07

1 Answers1

0

you should probably pre-test for null before doing anything.

// don't do anything if a null player bullet object
if( playerBullet == null )
   return;

As for using the sender and e parameters, you are not exposing enough code on those to show the event handlers triggering them... Maybe edit your existing question and post more details.

DRapp
  • 47,638
  • 12
  • 72
  • 142
  • That won’t really fix anything because the creation as far as I can tell is never generating a a callable object – Velarux Nov 10 '18 at 18:04