Motzy0446
Motzy0446

Reputation: 3

Game States in MonoGame

I'm a beginner to Monogame and I'm trying to find an efficient way to change game states. For example, when the player dies, the screen changes to the menu screen. When the player clicks a button, the screen changes to the game screen.

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace Jetpack;

public class Game1 : Game
{
    private GraphicsDeviceManager _graphics;
    GameScreen gameScreen = new GameScreen();
    MenuScreen menuScreen = new MenuScreen();
    string state = "menu";

    public Game1()
    {
        _graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        IsMouseVisible = true;
    }

    protected override void Initialize()
    {   
        if(state == "game")
        {
            gameScreen.Initialize();
        }

        if(state == "menu")
        {
            menuScreen.Initialize();
        }

        base.Initialize();
    }

    protected override void LoadContent()
    {
        _spriteBatch = new SpriteBatch(GraphicsDevice);
    }

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            Exit();
        
        Globals.kState = Keyboard.GetState();

        if(state == "game")
        {
            gameScreen.Update();
        }

        if(state == "menu")
        {
            menuScreen.Update();
            if(Globals.kState.IsKeyDown(Keys.A))
            {
                state = "game";
            }
        }
        

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {   
        Globals._spriteBatch.Begin();
        
        if(state == "game")
        {
            gameScreen.Draw();
        }

        if(state == "menu")
        {
            menuScreen.Draw();
        }

        Globals._spriteBatch.End();

        base.Draw(gameTime);
    }
}

I've tried this approach but when I set the state equal to "game" in the Update method it gives an error.

Upvotes: 0

Views: 98

Answers (0)

Related Questions