I'd like to build an engine in XNA, primarily for a 2D RPG. At first, I began abstracting out some classes and built a Sprite class which wrapped a Vector2 and a Texture2D, and tried loading in content from the Sprite class' constructor. However, this didn't work. Now, it appears that I have to load all of the sprites within the Game class' LoadContent method. Is there anyway around this? I'd like to separate the actual Game Content from the inner workings of the engine, if possible.


4 Answers 4


The LoadContent method is simply called after the graphics device has been initialized. You can load content at any point after that, not just in the LoadContent method.

If you were, for instance, to instantiate your sprite class within the LoadContent method, or within the Draw or Update calls, you wouldn't have any problem.

Now, as far as design goes, having the sprite load the content it needs typically isn't a good idea. To keep with the single responsibility principle, and dependency inversion principle, you might want to accept a Texture2D as a parameter to the Sprite constructor. That way you'll be able to have the same "BadGuy" sprite, but be able to pass it two different textures (for say, a red bad guy and a green bad guy).


You don't need to load all content within the LoadContent method, you could load it in a method called by that, or at pretty much any time after that (once the GraphicsDevice is set up).

A very simple example might be having a list or similar structure in your game engine, then before loading the user of the engine would add the locations and types of content to load. Then you'd call your engine's LoadContent method from your game's LoadContent method. The engine would then loop through the added resources and load them for use in the engine.

This is of course a simple example, you'd probably need some kind of resource manager to manage loading/unloading/making resources available to what needs them etc.


Back in the day when I was using XNA I need to load textures at runtime.

I just spent 1hr digging around trying to find this, it uses a stream to read the file from disk and then loads the stream into a texture2d and you can then pass that of to your spritebatch or do what u need with it.

 Dim Texture As Texture2D
 Using FS As New FileStream(imagepath, FileMode.Open, FileAccess.Read)
 FS.Seek(0, SeekOrigin.Begin)
 Texture = Texture2D.FromStream(GraphicsDevice, FS)
 End Using

Hope that helps or is close to what u need.


what if you have this constructor? (i mean, is this possible?)

Sprite(Microsoft.Xna.Framework.Content.ContentManager content){
    Texture2D something = content.Load<Texture2D>("someImages");
  • 2
    \$\begingroup\$ Answer if you know, comment if you guess. \$\endgroup\$
    – Anko
    Mar 12, 2013 at 11:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .