# XNA 4.0 How to change GraphicsDevice Default DepthStencilState Value

I want to change one of the deafult values of my GraphicsDevice to that:

GraphicsDevice.DepthStencilState.DepthBufferEnable = true;


But I know only to change it on runtime in the Draw method by putting this code (which means it's changing the value everytime that the compiler is running the draw method!):

DepthStencilState state = new DepthStencilState();
state.DepthBufferEnable = true;
GraphicsDevice.DepthStencilState = state;


Does someone know how to change it once in an officient way?

## 1 Answer

Unless you have something that 'resets' the DepthStencilState you only have to set it once. For example in your LoadContent method (because the GraphicsDevice should be initialized there).

A typical method that resets some of these states is using the SpriteBatch which uses its own set of states to draw things. So in the event you mix the spriteBatch to draw 2D with primitives/models in 3D there is nothing you can do about that, because these methods require different states to function.

It then best to set the correct states as efficient as possible. So instead of making the DepthState everytime, create a global variable for it so you don't have to recreate it every draw call. The GraphicsDevice.DepthStencilState checks if the new value equals to the one that is already set, to prevent overhead.

• You are totally right! The spritebatch was the reason for changing the states of the GraphicsDevice, thank you for your helpful respond! – Omer Eli Jan 11 at 23:53