Search code examples
c#xnamonogame

C#: Make a global static method


So, I've been developing a game in Monogame for quite a while, and I'm trying to optimize the code. One of the things that I was trying to optimize was the LoadContent method, which is only present on one of the classes (The Game one) and is used to load assets into the game.

And I thought: Wouldn't it be nice to have a global, static method in every class to load the content themselves, rather than having the Game class to load it for them?

Example:
How I load the content right now:

class.LoadContent(c) // c is ContentManager, a variable used for loading assets
class2.LoadContent(c) // LoadContent(c) is a static method
class3.LoadContent(c)
...

How I would like to:

allTheClassesThatNeedContent.LoadContent(c) // LoadContent(c) is still a static method
// Assets loaded in each and every class!

How can I do it like this? Or, is it even possible to do it like I want?


Solution

  • I have declared the ContentManager as public static in my main class (Game1 in a default project)

    public static ContentManager content;
    

    With this I can load any content in any class by

    Game1.content.Load<T>()
    

    Especially on bigger projects I do not suggest to load all the data in Game1' LoadContent() because you will probably load a lot of content which is not needed on startup (e.g. level data from not visited levels) and this will slow down the game launch significantly when the game gets bigger.

    Rather load the content if really needed like in the constructor.