我在XNA中遇到了NullReferenceException问题。我有4个职业:英雄,精灵,火球,Game1。通过调试,我发现问题发生在我的Fireball通过管道
加载内容之后。 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;
}
然后在我的Sprite类中我尝试通过ContentManager加载我的纹理
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)); ;
}
它给了我一个NullReferenceException在myTexture = theContentManager.Load(theAssetName);线。通过调试报告,我看到资产名称中有"火球",但ContentManager本身为空。我做错了什么?因为我是c#的新手,如果有人能告诉我应该添加哪些行和在哪里,我会很感激。如果有人需要一个完整的项目,它在这里https://www.dropbox.com/s/1e353e834rggj40/test.rar因为它有点大。
你没有调用LoadContent为火球从Game1这意味着你没有ContentManager。将此添加到Sprite类中:
public static ContentManager Cm;
然后在Game1
的LoadContent顶部Sprite.Cm = this.Content;
那么它应该工作得很好,因为你保存了ContentManager在Sprite类中供以后使用。