gpt4 book ai didi

c# - XNA 中的空引用异常

转载 作者:太空宇宙 更新时间:2023-11-03 11:27:37 25 4
gpt4 key购买 nike

我对 XNA 有疑问。我试图通过扩展和收缩让文本“呼吸”,但它无法正常运行。它编译得很好,但我一直收到“NullReferenceException:对象引用未设置为对象的实例”。一运行就报错。我有两个文件,Game1.cs 和 BreathingText.cs。

呼吸文本.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

最佳答案

您正在 Drawtext 方法 (Game1 game = new Game1();) 中创建 game1 类的新实例,因此永远不会为游戏的 spritebatch 分配值(它将是 )。

您应该在创建文本类时传入游戏对象的实例,然后在 drawtext 方法中使用它。

class BreathingText
{
private Game1 _Game1; // Use this were you have 'game' currently

public BreathingText(Game1 game)
{
_Game1 = game;
}

关于c# - XNA 中的空引用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8872417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com