ContentManager,XNA中的NullReferenceException

时间:2013-06-08 12:19:51

标签: xna nullreferenceexception

我在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)); ;
        }

它在myTexture = theContentManager.Load(theAssetName)中给了我一个NullReferenceException;线。通过调试报告,我看到资产名称中包含“Fireball”,但ContentManager本身为空。我究竟做错了什么?由于我是C#的新手,如果有人能告诉我应该添加哪些行以及在哪里,我将不胜感激。如果有人需要一个完整的项目,它就在这里https://www.dropbox.com/s/1e353e834rggj40/test.rar因为它有点大。

1 个答案:

答案 0 :(得分:1)

你没有从Game1调用火球的LoadContent,这意味着你没有ContentManager。 将其添加到您的Sprite类:

public static ContentManager Cm;

然后在Game1的LoadContent顶部

Sprite.Cm = this.Content;

那么它应该可以正常工作,因为你保存了ContentManager以供以后在Sprite类中使用。