0

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

我刚开始制作一个简单的游戏来学习 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(Content); 但这也不起作用。

任何帮助和解释表示赞赏,谢谢

4

2 回答 2

1

这不是 xna 游戏的常用构造函数...似乎您正在使用 hack 来让在 winform 中使用游戏类...如果您想使用这种方式...您传递了错误的参数或您的没有创建正确的图形设备管理器

创建 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";
    }
    ....
 }

您应该意识到游戏构造函数没有参数,并且图形设备管理器是在构造函数中创建的

编辑:我在想你的向导类可能不是一个游戏,而是一个 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();
    }
    ....
}

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

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

        Components.Add( new Wizard(this));
    }
 }
于 2013-08-09T19:58:55.147 回答
0

以这种方式工作

texture = Game.Content.Load<Texture2D>(textureName); 
于 2014-04-25T10:39:03.303 回答