I encountered this strange problem where my UI drawing to RenderTarget2D works for a couple seconds and then suddenly goes black.
This is the RenderTarget2D
function:
public RenderTarget2D RenderUi(SpriteBatch spriteBatch) {
RenderTarget2D renderTarget = new RenderTarget2D(Graphics, 1920, 1080);
Graphics.SetRenderTarget(renderTarget);
Graphics.Clear(Color.Transparent);
spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default);
/* Goes black even if commented out
- My draw calls
*/
spriteBatch.End();
Graphics.SetRenderTarget(null);
return renderTarget;
}
And this is the Draw
function:
public virtual void Draw(GameTime gameTime) {
RenderTarget2D uiRenderTarget = UserInterface.RenderUi(SpriteBatch);
/* Main SpriteBatch */
SpriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, SamplerState.PointClamp,
null, null, null, Camera.TransformMatrix());
World.Draw(gameTime, SpriteBatch);
Entities.Draw(gameTime, SpriteBatch);
SpriteBatch.End();
/* Ui SpriteBatch */
SpriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, SamplerState.AnisotropicClamp, DepthStencilState.Default);
if (Input.IsAction(Actions.DrawUI))
SpriteBatch.Draw(uiRenderTarget, new Rectangle(0, 0, Graphics.GraphicsDevice.Viewport.Width, Graphics.GraphicsDevice.Viewport.Height), Color.White);
SpriteBatch.End();
}
So if I hold down the DrawUI button the UI draws correctly and everything below but then it suddenly goes black, releasing the button shows that everything but that RenderTarget
still draws fine.
Why does this happen and what can I do to avoid that?
RenderTarget2D renderTarget = new RenderTarget2D(Graphics, 1920, 1080);
instead of creating a new one each frame. Then thanks that helped. \$\endgroup\$