2017-10-14 60 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

回答