我正在做一个C#课程,我不得不制作太空入侵者风格的游戏。我不确定如何,但我一直遇到这个错误
System.NullReferenceException
对象引用未设置为对象的实例
这是我目前的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.Serialization;
namespace Space_Invaders_Clone
{
public partial class Form1 : Form
{
int BulletsCreated = 0;
PictureBox[] bullets = new PictureBox[999];
public Form1()
{
InitializeComponent();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
//MessageBox.Show(e.KeyValue.ToString());
if (e.KeyValue == 37 && Turret.Left > 12)
{
Turret.Left = Turret.Left - 5;
}
if (e.KeyValue == 39 && Turret.Left < 593)
{
Turret.Left = Turret.Left + 5;
}
if (e.KeyValue == 32)
{
bullets[BulletsCreated] = new PictureBox();
bullets[BulletsCreated].Width = 2;
bullets[BulletsCreated].Height = 24;
bullets[BulletsCreated].BackColor = Color.Cyan;
bullets[BulletsCreated].Top = Turret.Top - 26;
bullets[BulletsCreated].Left = Turret.Left + Turret.Width / 2;
bullets[BulletsCreated].Enabled = true;
bullets[BulletsCreated].Visible = true;
this.Controls.Add(bullets[BulletsCreated]); //add to controls
BulletsCreated++;
}
}
private void BulletTimer_Tick(object sender, EventArgs e)
{
bullets[0].Top = bullets[0].Top - 10;
}
}
}
此行发生错误:
bullets[0].Top = bullets[0].Top - 10;
我做错了什么?
答案 0 :(得分:2)
在处理keyvalue 32之前调用方法BulletTimer_Tick
。因此,您尝试读取并更新不存在的地址0处的值。