Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Content.Load<> in a class/subclass

Tags:

c#

class

load

xna

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

like image 409
PeppeJ Avatar asked Dec 04 '22 23:12

PeppeJ


2 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 instantiate the Ship:

Ship ship = new Ship(this.Content);
like image 197
JoDG Avatar answered Dec 19 '22 15:12

JoDG


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.

like image 22
Andrew Russell Avatar answered Dec 19 '22 13:12

Andrew Russell