0

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

4

1 回答 1

1

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

public static ContentManager Cm;

然后在 Game1 的 LoadContent 顶部

Sprite.Cm = this.Content;

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

于 2013-06-08T12:47:19.843 回答