I'm wondering if there is anyway to use the "Content.Load<>" in a class that is not the game itself, say I want to load a texture from within the class, rather than sending the texture to it.
namespace ProjectGame1
{
public class Ship
{
public Texture2D texture;
public Ship()
{
this.texture = Content.Load<Texture2D>("ship");
}
}
}
That's an example of what I'm trying to achieve
You just need to pass your ContentManager to the Ship object:
public Ship(ContentManager content)
{
this.texture = content.Load<Texture2D>("ship");
}
From your game class you instantiate the Ship:
Ship ship = new Ship(this.Content);
First of all, I recommend not using DrawableGameComponent, my reasoning for this is outlined in this answer here.
Now, to make your code work as-is, you need to pass a ContentManager
into the constructor you are creating (see JoDG's answer). But to do this you must only construct it after the ContentManager
is ready. For Game
's content manager, this is during and after LoadContent
being called (so not in your game's contstructor or Initialize
method).
Now, you could do something like using DrawableGameComponent, which is much nicer: Just give your Ship
class a LoadContent
method, and call that from your game's LoadContent
(as you would do for Draw
and Update
).
If the texture that your ship uses is not part of your ship's state (ie: all ships use the same texture), you could even make it static, saving you from having to call LoadContent
on every ship you create. I have an example of this is this answer here, which also has a list of other useful information about Content Manager.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With