C# 使用GraphicsDevice.DrawUserPrimitives()后返回SpriteBatch.Draw()

C# 使用GraphicsDevice.DrawUserPrimitives()后返回SpriteBatch.Draw(),c#,xna,spritebatch,C#,Xna,Spritebatch,在我的2D XNA游戏中,我一直在尝试画三角形。我一直在学习教程 从GraphicsDevice.DrawUserPrimitives()返回spriteBatch.Draw()时,我收到System.InvalidOperationException “在执行任何绘制操作之前,必须在设备上设置有效的顶点缓冲区(如果使用索引基元,则为有效的索引缓冲区)。” 如果有人能指出发生这种情况的原因,我将不胜感激。您必须在DrawUserPrimitives()之前调用spriteBatch.End()。

在我的2D XNA游戏中,我一直在尝试画三角形。我一直在学习教程

从GraphicsDevice.DrawUserPrimitives()返回spriteBatch.Draw()时,我收到System.InvalidOperationException

“在执行任何绘制操作之前,必须在设备上设置有效的顶点缓冲区(如果使用索引基元,则为有效的索引缓冲区)。”


如果有人能指出发生这种情况的原因,我将不胜感激。

您必须在
DrawUserPrimitives()之前调用
spriteBatch.End()
。然后,在尝试发出另一个
spriteBatch.Draw()
之前,必须发出另一个
spriteBatch.Begin()

SpriteBatch.Begin()
为您设置所有缓冲区和暂存,以便提供轻松的渲染功能。只要触摸
图形设备
您就有可能对
SpriteBatch
可能不知道的内容进行更改,重新启动SpriteBatch有助于将管道重置为已知状态

在图形设备上执行更改当前渲染目标或清除目标等操作都可以

// Game1.FX is a static instance of Effect
Game1.FX.CurrentTechnique = Game1.FX.Techniques["Pretransformed"];

foreach (EffectPass pass in Game1.FX.CurrentTechnique.Passes)
{
    pass.Apply();

    Game1.GameInstance.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 1, VertexPositionColor.VertexDeclaration);
}

// Exception is thrown when we go back to spriteBatch.Draw()
spriteBatch.Draw(Textures.Get("Projectiles\\laser01"), new Rectangle((int)compartment.Position.X, (int)compartment.Position.Y,
    compartment.CompartmentWeapon.MaxRange, 2), null, laserColour, gunRotation - compartment.CompartmentWeapon.ArcLOS, Vector2.Zero, SpriteEffects.None, 1);