Switch scenes in monogame?

Calling Game.LoadContent() again is not really the best way to go about things. You don;t want to load all content again (though it will skip content it has already loaded if not unloaded previously).

A simple way to get started with different states in the game is to use a simple state machine. Declare an enum with the different game states.

enum GameState
{
    MainMenu,
    Gameplay,
    EndOfGame,
}

In your Game class, declare a member of the GameState type.

GameState _state;

In your Update() method, use the _state to determine which update to run.

void Update(GameTime deltaTime)
{
    base.Update(deltaTime);
    switch (_state)
    {
    case GameState.MainMenu:
        UpdateMainMenu(deltaTime);
        break;
    case GameState.Gameplay:
        UpdateGameplay(deltaTime);
        break;
    case GameState.EndOfGame:
        UpdateEndOfGame(deltaTime);
        break;
    }
}

Now define the UpdateMainmenu(), UpdateGameplay() and UpdateEndOfGame().

void UpdateMainMenu(GameTime deltaTime)
{
    // Respond to user input for menu selections, etc
    if (pushedStartGameButton)
        _state = GameState.GamePlay;
}

void UpdateGameplay(GameTime deltaTime)
{
    // Respond to user actions in the game.
    // Update enemies
    // Handle collisions
    if (playerDied)
        _state = GameState.EndOfGame;
}

void UpdateEndOfGame(GameTime deltaTime)
{
    // Update scores
    // Do any animations, effects, etc for getting a high score
    // Respond to user input to restart level, or go back to main menu
    if (pushedMainMenuButton)
        _state = GameState.MainMenu;
    else if (pushedRestartLevelButton)
    {
        ResetLevel();
        _state = GameState.Gameplay;
    }
}

In the Game.Draw() method, again handle the different game states.

void Draw(GameTime deltaTime)
{
    base.Draw(deltaTime);
    switch (_state)
    {
    case GameState.MainMenu:
        DrawMainMenu(deltaTime);
        break;
    case GameState.Gameplay:
        DrawGameplay(deltaTime);
        break;
    case GameState.EndOfGame:
        DrawEndOfGame(deltaTime);
        break;
    }
}

Now define the different Draw methods.

void DrawMainMenu(GameTime deltaTime)
{
    // Draw the main menu, any active selections, etc
}

void DrawGameplay(GameTime deltaTime)
{
    // Draw the background the level
    // Draw enemies
    // Draw the player
    // Draw particle effects, etc
}

void DrawEndOfGame(GameTime deltaTime)
{
    // Draw text and scores
    // Draw menu for restarting level or going back to main menu
}

You can extend this later on by using separate classes for the different game states.

7 Likes