您的一个绘图调用可能会引发异常。这将使您在不调用的情况下退出该方法spriteBatch.End()
,然后在下一次通过时,您会在spriteBatch.Begin()
. (虽然我想知道为什么第一个异常没有结束你的程序,但第二个却结束了。)
如果这是问题所在,一种解决方案是将绘图调用包装在try
/finally
块中:
spriteBatch.Begin();
spriteBatch.Draw(background, Vector2.Zero, Color.White);
try {
player.Draw(spriteBatch);
level1.Draw(spriteBatch);
} finally {
spriteBatch.End();
}
另一种可能性是您实际上不小心调用spriteBatch.Begin()
了两次。SpriteBatch
就我个人而言,我通过将对象包装在不同的类中来避免这样做。
前任:
internal sealed class DrawParams
{
private SpriteBatch mSpriteBatch;
private bool mBegin;
/// <summary>Calls SpriteBatch.Begin if the begin value is true. Always call this in a draw method; use the return value to determine whether you should call EndDraw.</summary>
/// <returns>A value indicating whether or not begin was called, and thus whether or not you should call end.</returns>
public bool BeginDraw()
{
bool rBegin = mBegin;
if (mBegin)
{
mSpriteBatch.Begin();
mBegin = false;
}
return rBegin;
}
/// <summary>Always calls SpriteBatch.End. Use the return value of BeginDraw to determine if you should call this method after drawing.</summary>
public void EndDraw()
{
mSpriteBatch.End();
}
}