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:
From your game class you instantiate the Ship:
If the class derive form
DrawableGameComponent
then you still can useGame.Content.Load<Texture2D>("ship");
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 theContentManager
is ready. ForGame
's content manager, this is during and afterLoadContent
being called (so not in your game's contstructor orInitialize
method).Now, you could do something like using DrawableGameComponent, which is much nicer: Just give your
Ship
class aLoadContent
method, and call that from your game'sLoadContent
(as you would do forDraw
andUpdate
).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.I think you'll need a reference to the Game object to get its
Content
member. This could either be passed in or you could make the game a Singleton.Okay I solved it, I used a different method since yours didnt quite work as I'd expect. What I did was make a "public static ContentManager asd;" and then assigned it to Game's ContentManager, and then it worked by redirecting it to "Game1.asd (Variable names are examples)
In order to get this to work, you'll need a
Constructor
that accepts a parameter of typeGame
. This will mean you'll need to add a reference toMicrosoft.Xna.Framework.Game
.