Reputation: 379
I'm having a problem with NullReferenceException in XNA. I have 4 classes: Hero, Sprite, Fireball, Game1. Through debugging I see that problem occurs after my Fireball loads content through pipe
class Fireball: Sprite
{
const int MAX_DISTANCE = 500;
public bool Visible = false;
Vector2 mStartPosition;
Vector2 mSpeed;
Vector2 mDirection;
public void LoadContent(ContentManager theContentManager)
{
base.LoadContent(theContentManager, "Fireball");
Scale = 0.3f;
}
Then in my Sprite class I'm trying to load through ContentManager my texture
class Sprite
{
//The asset name for the Sprite's Texture
public string AssetName;
//The Size of the Sprite (with scale applied)
public Rectangle Size;
//The amount to increase/decrease the size of the original sprite.
private float mScale = 1.0f;
//The current position of the Sprite
public Vector2 Position = new Vector2(0, 0);
//The texture object used when drawing the sprite
private Texture2D myTexture;
//Load the texture for the sprite using the Content Pipeline
public void LoadContent(ContentManager theContentManager, string theAssetName)
{
myTexture = theContentManager.Load<Texture2D>(theAssetName);
AssetName = theAssetName;
Source = new Rectangle(0, 0, myTexture.Width, myTexture.Height);
Size = new Rectangle(0, 0, (int)(myTexture.Width * Scale), (int)(myTexture.Height * Scale)); ;
}
And it gives me a NullReferenceException in myTexture = theContentManager.Load(theAssetName); line. Through debug report I see that the asset name has the "Fireball" in it, but the ContentManager itself gets null. What am I doing wrong? Since I am new in C# I would appreciate if somebody can tell me what lines should I add and where. If somebody needs a full project, it's here https://www.dropbox.com/s/1e353e834rggj40/test.rar Since it's a bit massive.
Upvotes: 0
Views: 306
Reputation: 44
You are not calling LoadContent for fireball from Game1 wich means you have no ContentManager. Added this to your Sprite class:
public static ContentManager Cm;
And then at the top of your LoadContent in Game1
Sprite.Cm = this.Content;
then it should work fine because you saved the ContentManager for later use in the Sprite class.
Upvotes: 1