Xna Screen Manager

I know there’s lot’s of this stuff over the internet but I keep bumping into people asking for this.

A way to easily switch from a Game Screen to a Menu or Options without having tons of flags and “if” clauses on the class Game.

I’ve made a small project with a Screen Manager. The ScreenManager is static and can contain Screens. Instead of having typical Draw Update functions drawing SpriteBatches on the Game class we should have something like this:

 protected override void Update(GameTime gameTime)
        {
            // Tell ScreenManager to Update
            SCREEN_MANAGER.Update(gameTime);
            base.Update(gameTime);
        }
 
        protected override void Draw(GameTime gameTime)
        {
            // Tell ScreenManager to draw
            SCREEN_MANAGER.Draw(gameTime);
 
            base.Draw(gameTime);
        }

This way we are telling the Screen Manager to handle the draws and Updates. And the ScreenManager then tell the active screen to Draw/Update.

In this sample if you press the keys ‘m’ or ‘n’ you can switch from screen1 to screen2 and vice-versa. Notice that the color changes, you are inside a different Screen now.

In order to add another screen it would be something simple as:

    class Screen3 : Screen
    {
        public Screen1(GraphicsDevice device) :base(device,"screen3")
        {
        }
 
        public override bool Init()
        {
            return base.Init();
        }
 
        public override void Shutdown()
        {
            base.Shutdown();
        }
 
        public override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);
        }
 
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
        }
    }

You can tell the Screen Manager to switch screen by doing:

SCREEN_MANAGER.goto_screen("screen3");

Screen Manager then calls the virtual function shutdown() of the current screen and then the init() of the requested Screen, so you might want to always override them for your purposes.

You’ll understand better by viewing the code itself. Use it in any way you want. I now this example may not be the best solution but it gives a good start to those wanting to implement their own.

Download the source.

EDIT:

(04-02-2010) Removed unused member _current; (Thanks Jason)

Back to Top