XNA SpriteBatch 实例化问题
我一直在 XNA 中练习某些技术,最近遇到了一个让我困惑的问题。我一直在我的一些 Windows 游戏项目中使用这种技术,突然之间出现了一个问题,我想我忽略了一些东西......
所以我创建了一个新的 Windows 游戏项目并添加了一个 XNA 游戏组件项目中,将组件添加到 Game1.cs 文件中。在 Componant 中创建并实例化一个 SpriteBatch 变量,然后尝试绘制一个简单的纹理来测试 spriteBatch。
这是我收到的运行时错误的图片: http://twitpic.com/3jp8t1 ...以及两个文件的完整源代码:pastebin.com/rFRkGKXJ
I've been practicing certain techniques in XNA and lately came across an issue that's just confusing me. I've been using this technique for a few of my Windows Game Projects and all of a sudden now theres a problem, I think i'm overlooking something...
So I created a fresh Windows Game Project and added a XNA Game Componant to the project, added the componant to the Game1.cs file. Created and instantiated a SpriteBatch variable in the Componant then tried to draw a simple texture to test the spriteBatch.
Here's a picture of the runtime error I get: http://twitpic.com/3jp8t1
...and the full source of the two files: pastebin.com/rFRkGKXJ
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我突然想到(您可以使用 Reflector 仔细检查我),XNA 初始化期间的调用顺序是这样的:
Initialize()
LoadContent()
在您的游戏组件中(从Game.Initialize
调用)LoadContent()
在您的游戏类中(从Game.Initialize< 调用) /code>)
(顺便说一下,这不是完整的列表。)
所以我猜测,通过在游戏的
LoadContent
函数中添加游戏组件,LoadContent您的游戏组件中的
未被调用,因此其SpriteBatch
未被创建。您可以通过在游戏组件的LoadContent
函数中添加断点来检查这一点。通常,您希望在游戏的
Initialize
函数中创建并添加游戏组件。(此外,您应该并且可能需要调用
LoadContent
和UnloadContent
中相应的base
函数。)我个人更喜欢避免使用
DrawableGameComponent
并创建我自己的独立类。这让我可以更直接地共享SpriteBatch
实例(而不必为每个组件创建实例),并且可以让我更明确地控制调用事物的顺序。Off the top of my head (you can double-check me using Reflector), the order of calls during XNA initialisation is this:
Initialize()
in your game classLoadContent()
in your game components (called fromGame.Initialize
)LoadContent()
in your game class (called fromGame.Initialize
)(This is not the full list, by the way.)
So I would guess that, by adding the game component in your game's
LoadContent
function, theLoadContent
in your game component is not being called so itsSpriteBatch
is not being created. You could check this by adding a breakpoint in your game component'sLoadContent
function.Generally you want to create and add your game components in your game's
Initialize
function.(Also you should, and possibly need to, call the respective
base
functions inLoadContent
andUnloadContent
.)Personally I prefer to avoid using
DrawableGameComponent
and just make my own free-standing class. This lets me share instances ofSpriteBatch
more directly (rather than having to create ones for each component) and it lets me more explicitly control the order things are called in.