2017-10-14 61 views
-2
public int level = 1; 
    public PictureBox[] invaders; 

    public void spawn(int level) 
    { 
     int f = 0; 

     invaders = new PictureBox[100]; 
     PictureBox invader = new PictureBox(); 
     Bitmap img = (WindowsFormsApplication1.Properties.Resources.SpaceInvader); 
     for (int n = 32; n < (4 + level)*32; n=n+32) 
     { 
      for (int i = 90; i < 400; i = i + 37) 
      { 
       invaders[f] = new PictureBox(); 
       invaders[f].Location = new Point(i, n); 
       invaders[f].Size = new Size(20, 15); 
       invaders[f].Image = img; 
       invaders[f].SizeMode = PictureBoxSizeMode.StretchImage; 
       invaders[f].BackColor = Color.Transparent; 

       this.Controls.Add(invaders[f]); 

       f++; 
      } 
     } 
     timer2.Interval = 10; 
     timer2.Start(); 
    } 
    private void timer2_Tick(object sender, EventArgs e) 
    { 
     for (int i = 0; i < invaders.Length; i++) 
     { 
      invaders[i].Location = new Point(invaders[i].Location.X + 1, invaders[i].Location.Y); 
     } 
    } 

错误:不断移动pictureboxes的阵列C#

An unhandled exception of type 'System.NullReferenceException' occurred in SpaceInvaders.exe

所有图像间移动一次,然后发生错误。任何解决方案

+0

哪一行抛出异常启动? –

+0

invaders [i] .Location = new Point(invaders [i] .Location.X + 1,invaders [i] .Location.Y); – space482

+0

并非侵略者阵列中的所有地方都被填满。为什么不使用List而不是数组? – NineBerry

回答