First things first: You are free to call the ContentManager at any point in your game cycle (you're not restricted to the use the LoadContent()
method created in the main class).
This doesn't solve your memory problem though, so on to part two:
If you run into memory issues because you have too much content loaded at the same time, you should only load the content that you actually need at that point in your game.
To free memory from loaded content, you can use Content.Unload()
to release all content that the ContentManager holds. Note: Texture2D.Dispose()Texture2D.Dispose()
does not free up memory for Textures that are loaded via the ContentManager- as the ContentManager is in control of the lifetime of its content! (Sidenote: one should call Dispose()
on content that is unmanaged -created without the ContentManager- though!)
A Content.Unload()
releases all the content it contains so one might separate "generic" game content from "level specific" game content. Luckily you are able to create your own instance of the ContentManager so you can control what content is kept and what content is unloaded, like so:
C#:
ContentManager levelContentManager = new ContentManager( Game.Services, Content.RootDirectory );
or VB.Net
levelContentManager As New ContentManager(Content.ServiceProvider, Content.RootDirectory)
Now use:
levelContentManager.Unload()
when your level is completed and the level specific content is no longer used.
See also:
An example application would be in a game like Street Fighter (only used as example, Street Fighter wasn't build in XNA). The "Generic ContentManager" holds generic data: the titlescreen, the "Get Ready, Fight!" letters and healthbars. The other "level ContentManager" only loads the sprite info of the selected chars and level.
When the characters and level object are created, have those objects load their content via the "level ContentManager". When the fight is over and the game goes back to the title screen: the "level ContentManager" unloads to free up the resources.
When the players start a new fight, the "level ContentManager" is used again to load the now selected characters and level data and the cycle repeats.
This way, the memory only holds the content it is actually using.