我正在为学校制作一款小游戏,我想用砖块中的实例制作一个列表。所以我这样做了。
public class Game1 : Game
{
public static SpriteBatch spriteBatch;
private GraphicsDeviceManager graphics;
private WreckingBall _wreckingBall;
private MouseHandler _mouse;
private bool _drag;
private List<Brick> _bricks;
但现在编译器说&#34; Field&#39; WreckingBall.Game1._bricks&#39;永远不会被赋予,并且将始终将其默认值为null&#34;
这是我的Brick类
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);
}
}
有谁知道我做错了什么?
答案 0 :(得分:2)
您需要在代码中的某处:
_bricks = new List<Brick>();
它的一个好地方是在构造函数中,但你甚至可以在私有变量部分初始化列表:
private List<Brick> _bricks = new List<Brick>();
答案 1 :(得分:1)
在Game
中实例化:
private List<Brick> _bricks = new List<Brick>();