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 sendi开发者_开发技巧ng 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 the class derive form DrawableGameComponent
then you still can use
Game.Content.Load<Texture2D>("ship");
In order to get this to work, you'll need a Constructor
that accepts a parameter of type Game
. This will mean you'll need to add a reference to Microsoft.Xna.Framework.Game
.
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
namespace ProjectGame1
{
public class Ship : DrawableGameComponent // Notice the class now inherits from
{ // DrawableGameComponent
public Texture2D texture;
public Ship(Game game)
: base(game) // <<---- Don't forget to pass Game to the base constructor
{
this.texture = game.Content.Load<Texture2D>("ship");
}
}
}
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)
精彩评论