我在代码中做错了什么?空引用异常错误



我正在做一个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;

我做错了什么?

处理键值 32 之前调用方法 BulletTimer_Tick。 因此,您尝试读取和更新地址 0 处不存在的值。

最新更新