Quirks with XNA ContentManager Load and Unload

I was recently experimenting with game state transitions and attempting to unload content when a screen was no longer needed. For example, I had a main menu screen which loaded assets to its own ContentManager on activation and unloaded the content when the screen transitioned off based on user input. This all worked fine until the main menu was asked to transition back on after the user was done playing the game.

What I found is that calling the ContentManager’s Unload method will call the Dispose method of all the resources for which it is responsible. You do not and should not manually call the Dispose method for content that has been loaded. However, a problem arises when you want to reuse something that has been unloaded without reinitializing the ContentManager. Even worse, the problem arises even if you call the Load method for a piece of content after it has been Unloaded.

For example:

I received an error on line 7 of the above paste because even though I reloaded the texture, the ContentManager will return the cached version of the already loaded texture (even though you called Unload!). Yes, the cached version is the one that got disposed!

One thought on “Quirks with XNA ContentManager Load and Unload

Leave a Reply

Your email address will not be published. Required fields are marked *