XNA有问题。我试图让文本通过扩展和收缩来“呼吸”,但它不能正确运行。它编译得很好,但我不断收到一个“NullReferenceException:对象引用未设置为对象的实例”。错误一旦运行。我有两个文件,Game1.cs和BreathingText.cs。XNA中的空引用异常
BreathingText.cs:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace TestingThings
{
class BreathingText
{
public void drawText(string textToDraw, int X, int Y)
{
int fontRestraint = 1;
Game1 game = new Game1();
GraphicsDeviceManager graphics = game.graphics;
SpriteBatch sB = game.spriteBatch;
SpriteFont font = game.gameFont;
Vector2 FontPos = new Vector2(X, Y);
Vector2 StrCenter = new Vector2(0,0); //font.MeasureString(textToDraw)/2;
sB.Begin();
sB.DrawString(font,
textToDraw,
FontPos,
Color.LightGreen,
0,
StrCenter,
1.0f,
SpriteEffects.None,
0.5f);
if (fontRestraint == 1)
{
font.Spacing += 0.25F;
}
else if (fontRestraint == 0)
{
font.Spacing -= 0.25F;
}
if (font.Spacing == 17)
{
fontRestraint = 0;
}
else if (font.Spacing == 0)
{
fontRestraint = 1;
}
sB.End();
}
}
}
唯一的例外发生在sB.Begin()
。我以为这是因为Game1.cs中的spriteBatch
没有初始化,但它在我看来应该是这样。这里的Game1.cs:
namespace TestingThings
{
public class Game1 : Microsoft.Xna.Framework.Game
{
public GraphicsDeviceManager graphics;
public SpriteBatch spriteBatch;
public SpriteFont gameFont;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
gameFont = Content.Load<SpriteFont>("Celestia");
}
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
{ this.Exit(); }
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
BreathingText breath = new BreathingText();
breath.drawText("test", graphics.GraphicsDevice.Viewport.Width/2, graphics.GraphicsDevice.Viewport.Height - 25);
base.Draw(gameTime);
}
}
}
我不知道为什么它不工作,因为它看起来像它应该。不过,我是一个新手,解决方案很可能是在我的鼻子下。我在Game1中的Draw方法中使用了BreathingText.cs代码,并且它运行良好,直到我将它移到它自己的类中。
任何帮助,将不胜感激。
感谢, MrAnthology
是否在您的代码或XNA代码中发生空引用异常? – 2012-01-15 18:56:15
它在我自己的BreathingText.cs中的'sBegin()'上发生,所以我假设这是我自己的做法。就像我说的,虽然,我是C#的新手,所以我仍然在学习如何调试这样的东西。 – MrAnthology 2012-01-15 18:59:44
我不使用XNA,但它看起来像'Game1.LoadContent'没有在基类的构造函数中调用。何时应该调用? – Groo 2012-01-15 19:01:18