如何从xna中的另一个类(不是主类)调用类中的加载内容方法
本文关键字:调用 方法 加载 xna 另一个 | 更新日期: 2023-09-27 18:19:25
我正在为学校制作一款游戏,里面有3个小游戏,我想把小游戏分成它们自己的类,这样主类就不会太拥挤,难以阅读,但每次我试图运行游戏时,它都会显示
"An unhandled exception of type 'System.NullReferenceException' occurred in Summer Assignment.exe"
当我拿出从类中加载内容的行时,游戏工作得很好我以前使用过类,所以这不是问题这里是代码
class Quiz
{
QuizQuestion no1;
ContentManager theContentManager;
SpriteBatch thespriteBatch;
int question = 0;
public void initialize()
{
no1 = new QuizQuestion();
}
public void LoadContent()
{
no1.LoadContent(this.theContentManager);
}
在我从load content方法加载内容的类中是
public void LoadContent(ContentManager theContentManager)
{
font = theContentManager.Load<SpriteFont>("Font2");
}
类在主游戏类中正确加载,我在添加下一个类之前运行它以确保
您需要为您的字段分配实际对象。如果你看Quiz.theContentManager
,你会注意到你从来没有给它赋值。您可以通过从Game1
传递这些来解决这个问题。例如,Game1应该是这样的:
public class Game1 : Microsoft.Xna.Framework.Game
{
Quiz quiz;
protected override void LoadContent()
{
quiz.LoadContent(Content);
}
protected override void Update(GameTime gameTime)
{
quiz.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
quiz.Draw(spriteBatch, gameTime);
}
}
那么你的Quiz类应该是这样的(注意,使用这种方法,你不需要任何XNA类字段):
public class Quiz
{
QuizQuestion no1 = new QuizQuestion();
public void LoadContent(ContentManager content)
{
no1.LoadContent(content);
}
public void Update(GameTime gameTime)
{
// Perform whatever updates are required.
}
public void Draw(SpriteBatch spriteBatch, GameTime gameTime)
{
// Draw whatever
}
}