【发布时间】:2013-02-13 18:36:48
【问题描述】:
我正在创建一个 xna 游戏,它可以正常编译,但是当它到达 spriteBatch.Begin(); 时会抛出 nullreferenceexception;在我的 spritemanager 类(这是一个可绘制的游戏组件)中。我认为 loadContent 没有运行,导致 spritebatch 未初始化,但我不确定如何让它运行。
SpriteManager 加载内容代码:
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(Game.GraphicsDevice);
player = new Player(Game.Content.Load<Texture2D>("Images/asteroids_player"),
new Vector2(Game.Window.ClientBounds.X / 2, Game.Window.ClientBounds.Y / 2),
Vector2.Zero,
0f,
new Point( 27, 40 ),
new Point( 1, 1 ),
new Point( 1, 2 ));
asteroidList = new List<Asteroid>();
base.LoadContent();
}
SpriteManager 绘制代码:
public override void Draw(GameTime gameTime)
{
spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend); // error thrown here
player.Draw(gameTime, spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
游戏1代码:
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteManager spriteManager;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// Creates and loads a SpriteManager to update/draw sprite objects
spriteManager = new SpriteManager(this);
Components.Add(spriteManager);
base.LoadContent();
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
base.Draw(gameTime);
}
【问题讨论】:
-
你能发帖
Class Player(Texture2d texture2d.....)吗? -
NullReferenceException的几乎所有情况都是相同的。请参阅“What is a NullReferenceException in .NET?”获取一些提示。 -
如果您认为 LoadContent 无法运行,您应该亲自尝试调试。在那里下一个断点,看看它是否没有运行。
标签: c# xna runtime-error