How To: Pause a Game

Demonstrates how to add pause functionality to a game.

The Complete Sample

The code in this topic shows you the technique. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample.

Adding Pause Functionality to a Game

To add pause functionality to a game

  1. Derive a class from Game.

  2. Add a variable to track the pause state.

    private bool paused = false;
  3. Add a variable to track the state of the pause key.

    private bool pauseKeyDown = false;
  4. Add a function to poll the state of the pause key with Keyboard.GetState and KeyboardState.IsKeyDown.

    If the key has changed from down to up, toggle the pause state.

    private void checkPauseKey(KeyboardState keyboardState, GamePadState gamePadState)
        if (keyboardState.IsKeyDown(Keys.P) || (gamePadState.Buttons.Y == ButtonState.Pressed))
            pauseKeyDown = true;
            paused = true;
        else if (pauseKeyDown)
            pauseKeyDown = false;
            paused = false;
  5. Add a conditional around any update code so it will be called only if the game is not paused.

    // Pause if the Guide is up, or if the user has paused
    if ((paused == false) && (Guide.IsVisible == false))

Bb195026.bp(en-US,XNAGameStudio.30).gifBest Practice

You might choose to implement a menu of options to display when a game is paused. This might include options to resume, purchase, save, or quit the game. In multiplayer games, pausing will usually disable local input without pausing the game for remote players.

Some situations in which you may want to pause the simulation update or input are when:

Community Additions