我通常会在XNA论坛上寻求帮助,但他们现在已经失败了,所以我来到这里.
我正在制作一个新的XNA游戏,我希望有一个玩家类.目前我有一个主要的游戏类叫Dots.这代表了主要游戏.这就是我Player班级目前的布局:
namespace Dots
{
class Player : Microsoft.Xna.Framework.Game
{
Texture2D PlayerTexture;
Vector2 PlayerPosition;
public Player()
{
Content.RootDirectory = "Content";
PlayerTexture = Content.Load<Texture2D>("Player");
PlayerPosition = Vector2.Zero;
}
public void Update()
{
}
public void Draw(SpriteBatch SpriteBatch)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
但我收到一个错误,我无法解决如何解决.错误是:
加载"播放器"时出错.找不到GraphicsDevice组件.
它把它扔在这条线上:PlayerTexture = Content.Load<Texture2D>("Player");.
我在主游戏课中看到有这一行:Graphics = new GraphicsDeviceManager(this);但我不知道如何处理它.我把它传给我的Player班级,还是什么?
任何帮助表示赞赏,谢谢.
首先,您似乎缺乏对类(和命名空间)如何工作的理解.我建议(正如我在对你的另一个问题的评论中所做的那样)开发一个不需要课程的简单游戏,首先.
现在来谈谈代码中的问题:
首先,为了加载内容,需要初始化图形设备.LoadContent在调用之前它不会被初始化Microsoft.Xna.Framework.Game.这在文档中解释:
Initialize调用此方法.此外,只要需要重新加载游戏内容,就会调用它,例如发生DeviceReset事件时.在调用LoadContent之前,不应访问GraphicsDevice.
所以移动你的加载代码:
protected override void LoadContent()
{
PlayerTexture = Content.Load<Texture2D>("Player");
PlayerPosition = Vector2.Zero;
base.LoadContent();
}
Run Code Online (Sandbox Code Playgroud)
注意它是如何覆盖(受保护方法).我真的不想在这里解释这意味着什么,但我建议你找出答案.
此外,你会发现Draw并且Update应该被类似地重写,因为它们将从XNA调用.
现在,这是重要的一点:如果您从XNA 类继承您的游戏类,我刚刚告诉您的内容Game.通过将其称为"播放器",您表示对类的工作方式存在误解.
如果您正在制作"玩家"课程,请查看您在其他问题的答案中所说的内容.
更新:对于旧版本的 XNA,这个答案显然是正确的。请参阅安德鲁·罗素 (Andrew Russell) 的回答,了解当前正在使用的内容。
尝试重写 LoadGraphicsContent 方法来加载您的内容。如本教程所示。
protected override void LoadGraphicsContent(bool loadAllContent)
{
if (loadAllContent)
{
spriteBatch = new SpriteBatch(graphics.GraphicsDevice);
// TODO: Load any ResourceManagementMode.Automatic content
t2dMap = content.Load<Texture2D>(@"content\textures\map_display");
t2dColorKey = content.Load<Texture2D>(@"content\textures\map_colorkey");
}
// TODO: Load any ResourceManagementMode.Manual content
}
Run Code Online (Sandbox Code Playgroud)