Drakon0168
Drakon0168

Reputation: 28

How do you call a load content method in a class from another class (not main class) in xna

I am making a game for school and it has 3 mini-games inside of it i wanted to separate the mini-games into their own class so that the main class wouldn't become too crowded and hard to read but every time I try to run the game it says

"An unhandled exception of type 'System.NullReferenceException' occurred in Summer Assignment.exe"

the game works fine when I take out the line that loads content from the class and I have used classes before so that isnt the problem here is the code

class Quiz
{
    QuizQuestion no1;
    ContentManager theContentManager;
    SpriteBatch thespriteBatch;
    int question = 0;

    public void initialize()
    {
        no1 = new QuizQuestion();
    }

    public void LoadContent()
    {
        no1.LoadContent(this.theContentManager);
    }

and in the class that I am loading content from the load content method is

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

the class is loaded correctly in the main game class i ran it before adding the next class to be sure

Upvotes: 0

Views: 755

Answers (1)

itsme86
itsme86

Reputation: 19486

You need to assign your fields actual objects. If you look at Quiz.theContentManager, you'll notice that you never actually assign it a value. You can fix this by passing the ones in from Game1. For instance, Game1 should look like this:

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);
    }
}

Then your Quiz class should look like this (note that you don't need class fields for any of the XNA stuff with this approach):

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
    }
}

Upvotes: 1

Related Questions