" in a class that is not the game itself, I will ...">

Using Content.Load <> in a class / subclass

I am wondering if, in any case, using "Content.Load <>" in a class that is not the game itself, I will say that I want to load the texture from the class, and not send the texture to it.

 namespace ProjectGame1 { public class Ship { public Texture2D texture; public Ship() { this.texture = Content.Load<Texture2D>("ship"); } } } 

This is an example of what I'm trying to achieve.

+4
source share
6 answers

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 create a ship instance:

 Ship ship = new Ship(this.Content); 
+8
source

Firstly, I recommend not using DrawableGameComponent , my arguments for this are described in this answer here .

Now, to make your code work as is, you need to pass the ContentManager to the constructor you are creating (see JoDG answer ). But for this you should build it only after the ContentManager ready. For the Game content manager, this happens during and after the LoadContent , which is called (and not in your game counter constructor or Initialize method).

Now you can do something like using DrawableGameComponent, which is much nicer: just give your Ship class a LoadContent method and call it from your LoadContent game (as you would for Draw and Update ).

If the texture your ship uses is not part of your vessel state (i.e. all ships use the same texture), you can even make it static, eliminating the need to call LoadContent on every ship you create. I have an example of this this answer here , which also has a list of other useful information about Content Manager.

+4
source

If the class displays the DrawableGameComponent form, you can still use Game.Content.Load<Texture2D>("ship");

+3
source

For this to work, you will need a Constructor that takes a parameter of type Game . This will mean that you need to add a link 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"); } } } 
+1
source

I think you will need a reference to the Game object to get its Content member. It can either be transmitted, or you can make a Singleton game.

0
source

Well, I solved it, I used a different method, since yours did not work as I expected. What I did is to do "public static ContentManager asd"; and then assigned it to the Game ContentManager, and then it worked, redirecting it to "Game1.asd (Variable names - examples)

0
source

Source: https://habr.com/ru/post/1344779/


All Articles