jonathanpeppers
jonathanpeppers

Reputation: 26505

XNA Texture2D caching

Is a class such as this necessary?

public class ContentCache
{
    private readonly ContentManager _content;
    private readonly Dictionary<string, Texture2D> _textureCache = new Dictionary<string, Texture2D>();

    public ContentCache(ContentManager content)
    {
        _content = content;
    }

    public Texture2D Load(string assetName)
    {
        Texture2D texture = null;
        if (!_textureCache.TryGetValue(assetName, out texture))
        {
            _textureCache[assetName] =
                texture = _content.Load<Texture2D>(assetName);
        }
        return texture;
    }
}

I am curious if ContentManager.Load<Texture2D>() does it's own caching internally. I don't want to double-cache things.

Note:

Our XNA game is 2D and going to run on WP7 and Windows, and also iOS and OSX using MonoGame.

MonoGame may function differently than XNA in Windows, but I can probably browse it's source to find that out.

Upvotes: 4

Views: 2238

Answers (3)

bodge
bodge

Reputation: 41

It should be noted that Mono class ContentManager now also does caching.

Added sometime in 2012. For future reference.

Upvotes: 1

Oyvind Andersson
Oyvind Andersson

Reputation: 362

Just cache what needs to be cache in the first LoadContent method, by using some precache string array, like:

// Preload assets
static readonly string[] preloadAssets =
{
     "Textures\\texture1",
};

protected override void LoadContent()
{
    foreach ( string asset in preloadAssets )
    {
        Content.Load<object>(asset);
    }
}

Something like that mayhaps!

Upvotes: 0

cwharris
cwharris

Reputation: 18125

The class is unnecessary. ContentManager does this on your behalf.

Source:

http://forums.create.msdn.com/forums/p/31383/178975.aspx

Note:

As far as Mono goes... I'm sure the implementations mirror each other quite well, but I can't be certain on this occasion.

Also, if you WANT to re-load an asset, you could use an additional ContentManager and throw it away afterward.

Upvotes: 4

Related Questions