Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

When using this code:

public static Texture2D ShowHealthBar(SpriteBatch spriteBatch,Texture2D empty, Texture2D full, float health)
    {

        spriteBatch.Begin();
        RenderTarget2D healthBarTarget = new RenderTarget2D(Game1.graphics.GraphicsDevice, full.Width, full.Height);


        Game1.graphics.GraphicsDevice.SetRenderTarget(healthBarTarget);
        spriteBatch.Draw(empty, new Vector2(0, 0), Color.White);
        Game1.graphics.GraphicsDevice.SetRenderTarget(null);

        spriteBatch.End();
        return (Texture2D)healthBarTarget;
    }

the texture is purple.

When inserting Game1.graphics.GraphicsDevice.Clear the texture has the clear color.

Why doesn't the sprite batch work?

share|improve this question

closed as too localized by Byte56, bummzack, Anko, msell, ClassicThunder Apr 25 '13 at 15:44

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

2  
Try moving your calls to GraphicsDevice.SetRenderTarget outside of your calls to SpriteBatch.Begin and SpriteBatch.End. –  Seth Battin Apr 22 '13 at 16:43
    
Thank you that worked :) –  user1990950 Apr 22 '13 at 17:09
    
No problem, let me write this up in an answer. –  Seth Battin Apr 22 '13 at 17:17

1 Answer 1

The default behavior of SpriteBatch is to save its actual call to the GPU until you call .End(), rather than immediately (available by optional argument) when you call .Draw(). This allows it to reduce the total number of draw calls it makes, which is an important optimization. But switching the render target back before calling End() means that the draw goes to the wrong place, not the RenderTarget that was set when you called Draw().

So, call End() before switching the target back to the default.

share|improve this answer

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