繁体   English   中英

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

[英]How do you call a load content method in a class from another class (not main class) in 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);
    }

在我要从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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM