【问题标题】:How do you call a load content method in a class from another class (not main class) in xna如何从 xna 中的另一个类(不是主类)调用一个类中的加载内容方法
【发布时间】:2014-08-24 22:37:31
【问题描述】:

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

该类已在主游戏类中正确加载,我在添加下一个类之前运行它以确保

【问题讨论】:

    标签: c# xna


    【解决方案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
        }
    }
    

    【讨论】:

    • 谢谢,过去几天我一直在到处寻找解决方案,但找不到我遇到的具体问题
    猜你喜欢
    • 1970-01-01
    • 2012-09-06
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多