When i Draw a texture2d or a font with spriteBatch and also draw GraphicsDevice.DrawIndexedPrimitives, the frame is draw weird

SpriteBatch  spriteBatch = new SpriteBatch(GraphicsDevice);
BasicEffect basicEffect = new BasicEffect(GraphicsDevice);

protected override void Draw(GameTime gameTime)
    RasterizerState rasterizerState = new RasterizerState();
    rasterizerState.CullMode = CullMode.None;
    GraphicsDevice.RasterizerState = rasterizerState;

    //for(...) {
    GraphicsDevice.Indices = indexBuffer;

    foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
        GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 8, 0, 20);
    // } end for 

    spriteBatch.DrawString(MainFont, "FPS: " + Math.Round(1 / (float)gameTime.ElapsedGameTime.TotalSeconds, 2), new Vector2(200, 10), Color.Red); 


How can i solve this ?

  • \$\begingroup\$ @SethBattin i am already using spriteBatch.Begin(); / spriteBatch.End(); outside of the DrawIndexedPrimitives, that answer doesn't apply to my situation, at least i don't think it does ? the guy on the quiestion you linked me had Begin() in the very first line, and then End() at the last line, my case is different here \$\endgroup\$ – dimitris93 Jan 24 '15 at 23:27
  • 1
    \$\begingroup\$ That linked question may be too succinct. In any case, the answer you already selected is correct, that is the cause of the problem. I also had trouble finding a good match when I searched. \$\endgroup\$ – Seth Battin Jan 25 '15 at 0:39

This is because the sprite batch hijacks the graphics device's states when you use it. You need to cache them before using the sprite batch and then restore them afterwards. (Or you can set them directly afterwards without caching if you know the ones you want to use.)

// cache device states
var blendState = GraphicsDevice.BlendState;
var depthStencilState = GraphicsDevice.DepthStencilState;
var samplerState = GraphicsDevice.SamplerStates[0];

// use your SpriteBatch

// restore device states
GraphicsDevice.BlendState = blendState;
GraphicsDevice.DepthStencilState = depthStencilState;
GraphicsDevice.SamplerStates[0] = samplerState;
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.