字段永远不会分配给,并且将始终具有其默认值



我正在为学校做一个小游戏,我想用类砖块的实例列出一个列表。所以我这样做了。

 public class Game1 : Game
    {
        public static SpriteBatch spriteBatch;
        private GraphicsDeviceManager graphics;
        private WreckingBall          _wreckingBall;
        private MouseHandler          _mouse;
        private bool                  _drag;
        private List<Brick> _bricks;

但是现在编译器说"字段'WreckingBall.Game1._bricks'永远不会分配给,并且将始终具有其默认值 null"

这是我的砖课

class Brick : DrawableGameComponent
    {
        public Texture2D _texture { get; set; }
        public Vector2 _position { get; set; }

         public Brick(Game game)
            : base(game)
        {
            Game.Components.Add(this);
            this._position = _position;
        }
         protected override void LoadContent()
         {
             _texture = Game.Content.Load<Texture2D>("Brick");
             base.LoadContent();
         }
         public override void Update(GameTime gameTime)
         {
             _position = new Vector2(100, 100);
             base.Update(gameTime);
         }
         public override void Draw(GameTime gameTime)
         {
                 Game1.spriteBatch.Draw(_texture, _position, Color.White);
             base.Draw(gameTime);
         }
    }

有谁知道我做错了什么?

在代码中的某个地方你需要:

_bricks = new List<Brick>();

一个好地方是在构造函数中,但你甚至可以在私有变量部分初始化列表:

private List<Brick> _bricks = new List<Brick>();

Game 中实例化它:

private List<Brick> _bricks = new List<Brick>();

相关内容

最新更新