我通常会在 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)
{
}
}
}
但是我遇到了一个错误,我不知道如何解决。错误是:
Error loading "Player". GraphicsDevice component not found.
它在这一行抛出:PlayerTexture = Content.Load<Texture2D>("Player");
.
我在主游戏类中看到这一行:Graphics = new GraphicsDeviceManager(this);
但我不知道该怎么办。我是否将它传递给我的 Player
类,还是什么?
感谢任何帮助,谢谢。
最佳答案
首先,您似乎不了解类(和 namespace )的工作原理。我建议(正如我在对您的其他问题的评论中所做的那样)首先开发一款不需要类(class)的简单游戏。
现在谈谈你代码中的问题:
首先,为了加载内容,图形设备需要已经初始化。在 Microsoft.Xna.Framework.Game
中调用 LoadContent
之前,它不会被初始化。这是 explained in the documentation :
This method is called by Initialize. Also, it is called any time the game content needs to be reloaded, such as when the DeviceReset event occurs. You should not access the GraphicsDevice until LoadContent is called.
所以移动你的加载代码:
protected override void LoadContent()
{
PlayerTexture = Content.Load<Texture2D>("Player");
PlayerPosition = Vector2.Zero;
base.LoadContent();
}
注意它是如何覆盖( protected 方法)的。我真的不想在这里解释这意味着什么,但我建议你去了解一下。
此外,您会发现 Draw
和 Update
应该被类似地覆盖,因为它们将从 XNA 调用。
现在,重要的一点是:如果您从 XNA Game
继承您的游戏类,我刚才告诉您的内容将适用类(class)。将其称为“Player”表明您误解了类的工作方式。
如果您正在制作“玩家”类,请查看 your other question 的答案中告诉您的内容.
您还可以找到 this recent question值得一读。
关于c# - 我的 C# XNA 游戏的玩家类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3893796/