How do I load content after the game starts?

I am having a problem in my game where I cant figure out how to load content after the game has started. I have a basic RenderObject set up that has a Texture2D, location, etc, and a function that loads stuff

public void LoadContent(ContentManager content)
			image = content.Load<Texture2D>(graphic);

image is the texture2D, every renderObject has this function and it’s called during the game start.

protected override void LoadContent()
			// Create a new SpriteBatch, which can be used to draw textures.
			spriteBatch = new SpriteBatch(GraphicsDevice);

			for (int i = 0; i < RenderObject.renderObjects.Count; i++)

This only loads content for the initially existing objects, and if I create any other objects it crashes because they want to pull non-existent content. Should I be doing this a certain way so I don’t have to have one huge LoadContent where I have to manually load every single graphic at the start of the game?

1 Like

You can load content any time you want. When you create a new RenderObject later, you will need to manually call the LoadContent(Content) method on that new RenderObject.

1 Like

Thank you, but how do I pass the Content into LoadContent when I’m loading it later? It says use this.Content, but I dont know how to call or reference it out of that function.

You’ll have to pass it in from somewhere. Whether that is through a function parameter, a stack of property accesses all the way up to the top, a singleton, or some global IOC like storage.

How would I do this?

  • Options
    • Pass the ContentManager instance around in your constructors, method calls, etc.
      • Works, you still have to find the ContentManager instance though
    • Have a access to a parent, and through some inevitable chain of Parent.Parent.Parent finally reach a Parent who has the ContentManager
      -Don’t do this
    • Store it in a singleton or The “Biblical” version
      • Works, easy to use
      • Refactoring singleton ladden code sucks
    • Use IOC paradigm
      • Lots of bloated libs for it out there
      • Boils down to “singleton and instance management”
      • If you use something light then refactoring is easy as you can gut the IOC container and reroute as needed
      • Here’s mine (it works for a 200k line project, it’ll work for all)