How to: Load Resources

This article demonstrates how to load resources and ensure that they will be reloaded at the appropriate times.

To load resources and ensure they will be reloaded when necessary

  1. Derive a class from Game.

  2. Override the LoadGraphicsContent method of Game.

  3. In the LoadGraphicsContent method, if the loadAllContent parameter is true, load your resources that are ResourceManagementMode.Automatic, including resources loaded by the ContentManager. Regardless of the value of loadAllContent, resources with ResourceManagementMode.Manual will need to be loaded every time LoadGraphicsContent is called.

    protected override void LoadGraphicsContent( bool loadAllContent )
    {
        if (loadAllContent)
        {
            box = content.Load<Model>( "box" );
        }
    
    }
    
  4. Override the UnloadGraphicsContent method of Game.

  5. In the UnloadGraphicsContent method, if the unloadAllContent parameter is true, unload your resources that are ResourceManagementMode.Automatic, including resources loaded by the ContentManager. Regardless of the value of unloadAllContent, resources with ResourceManagementMode.Manual will need to be unloaded every time UnloadGraphicsContent is called.

    protected override void UnloadGraphicsContent( bool unloadAllContent )
    {
        if (unloadAllContent == true)
        {
            content.Unload();
        }
    }
    

The Complete Example

//Game1.cs
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using Microsoft.Xna.Framework.Content;

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    ContentManager content;

    Model box;

    public Game1()
    {
        graphics = new GraphicsDeviceManager( this );
        content = new ContentManager( Services );
    }

    protected override void Initialize()
    {
        base.Initialize();
    }

    protected override void LoadGraphicsContent( bool loadAllContent )
    {
        if (loadAllContent)
        {
            box = content.Load<Model>( "box" );
        }

    }

    protected override void UnloadGraphicsContent( bool unloadAllContent )
    {
        if (unloadAllContent == true)
        {
            content.Unload();
        }
    }

    protected override void Update( GameTime gameTime )
    {
        base.Update( gameTime );
    }

    protected override void Draw( GameTime gameTime )
    {
        graphics.GraphicsDevice.Clear( Color.CornflowerBlue );

        base.Draw( gameTime );
    }
}