如何在xna中从另一个类(不是主类)调用类中的加载内容方法

时间:2014-08-24 22:37:32

标签: c# xna

我正在为学校制作游戏,里面有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);
    }

在我从加载内容方法加载内容的类中

public void LoadContent(ContentManager theContentManager)
{
    font = theContentManager.Load<SpriteFont>("Font2");
}

在主游戏类中正确加载类我运行它然后再添加下一个类来确保

1 个答案:

答案 0 :(得分:1)

您需要为字段分配实际对象。如果你看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
    }
}
相关问题