XNA - 尝试在另一个类中加载纹理总是会找不到GraphicsDevice组件

时间:2013-08-09 14:48:33

标签: c# xna textures texture2d

我已经阅读了许多与此类似问题的不同解决方案,但我找不到适用于我的解决方案。

我刚刚开始制作一个简单的游戏来学习XNA的基础知识,但是我无法在另外一个类中加载纹理。我试过这个:

编辑:这不是主要的课程,因为我没有那么清楚

class Wizard
{
    // Variables
    Texture2D wizardTexture;
    GraphicsDeviceManager graphics; // I added this line in later, but it didn't seem to do anything

    public Wizard(ContentManager content, GraphicsDeviceManager graphics)
    {
        this.graphics = graphics;
        Content.RootDirectory = "Content";
        LoadContent();
    }

    protected override void LoadContent()
    {
        wizardTexture = Content.Load<Texture2D>("Wizard"); // Error is here
        base.LoadContent();
    }

我也试过制作类似

的方法
public Texture2D Load(ContentManager Content)
{
     return Content.Load<Texture2D>("Wizard");
}

然后有wizardTexture = Load(内容);但这也不起作用。

感谢任何帮助和解释,谢谢

2 个答案:

答案 0 :(得分:1)

这不是xna游戏的常用构造函数......似乎你正在使用hack来让winform中的游戏类使用...如果你想用那种方式......你错了参数或你没有正确创建graphicsdevicemanager

创建xna游戏的常用方法是定义这两个文件:

 // program.cs file
 static class Program
    {
        static void Main(string[] args)
        {
            using (Game1 game = new Game1())
            {
                game.Run();
            }
        }
    }


 // Game1.cs file
 public class Game1 : Microsoft.Xna.Framework.Game {
    GraphicsDeviceManager graphics;

    public Game1( ) {
        graphics = new GraphicsDeviceManager( this );
        Content.RootDirectory = "Content";
    }
    ....
 }

你应该意识到游戏构造函数没有参数,并且在构造函数中创建了graphicsdevicemanager

编辑:我在想,也许你的向导类不是游戏,而是GameComponent或DrawableGameComponent,在这种情况下应该是:

class Wizard : DrawableGameComponent {
    Texture2D wizardTexture;

    public Wizard(Game game) : base(game)
    {
    }

    protected override void LoadContent()
    {
       wizardTexture = Content.Load<Texture2D>("Wizard"); // Error is here
        base.LoadContent();
    }
    ....
}

然后在初始化对象时在主游戏类中...您可以添加将它添加到Components集合中。

 class Game1: Game {
    ....
    public override void Initialize() {

        Components.Add( new Wizard(this));
    }
 }

答案 1 :(得分:0)

以这种方式工作

texture = Game.Content.Load<Texture2D>(textureName); 
相关问题