Creating Your First MonoGame Project

Creating Your First MonoGame Project

In this tutorial, we'll look at how to get our first game up and running with MonoGame using the MonoGame template.

Once we have our game up and running, we'll look at the code included in the template to see what we're working with. Hang on tight because, in a few short minutes, you will have made your first game! (If you count a blue screen as a game, that is.)

Using the MonoGame Template

Start by opening Visual Studio. You should see the start page, shown below:

VisualStudioStartPage.png

Click on the option to Create a new project.

CreateANewProject.png

On this page, you'll want to pick the right template to start your MonoGame project off on the right foot. There are a couple of viable options, but the one I'll recommend for now is the one called MonoGame Cross-Platform Desktop Application.

If you're having a hard time finding it, you can use the dropdowns at the top to filter down the list of options. It should be in the C# language category and the MonoGame project type category.

There are several additional MonoGame templates in here. One is the MonoGame Windows Universal XAML Application template, which could also work for these tutorials, though it uses DirectX instead of OpenGL. There are also templates for mobile apps and for libraries that are shared across projects. That MonoGame Cross-Platform Desktop App is your best choice for getting started, but there is a time and place for these others later.

Once you've chosen the template, press Next to advance to the next page:

ConfigureNewProject.png

On this page, you'll configure your project. Most of these settings won't make a huge difference as you start working in MonoGame. You can mostly pick whatever you feel like.

I suggest giving your new game a reasonable name so you can remember it later.

You can pick any location to save your project, though the default option is a decent one. (But take note of where it is. It isn't an obvious spot if you haven't done much in Visual Studio before, and you may need to hunt it down on your file system at some point.)

I typically check the box for Place solution and project in the same directory if I know there is only ever going to be a single project in my solution, which will be the case for now. It can be changed later, though it isn't the simplest thing to do.

Once you've got these settings the way you want, press Create to get Visual Studio to make the new project.

Visual Studio will open up the full UI and present you with your program. It may not have anything in the main code editor window initially, but that's okay for right now. We'll fix that in a moment.

Running Your First Game

At this point, we already have a working "game" that we could run immediately. It won't do anything fancy, but it exists!

Before we dive into the code to analyze what just came out of the project template, let's run our new game and see it in action.

There are multiple ways to do this.

1. Press F5.
2. Choose Debug > Start Debugging from the main menu.
3. Press the dark green arrow button in the main toolbar near the top of the screen.

Any of these should compile and run your game, and after doing so, you should see your game, which will look something like this:

NewGame.png

There won't be much you can do with your new game just yet. We haven't programmed it to do anything. So when you're done admiring the pretty cornflower blue rectangle, close it out and go back to Visual Studio.

Understanding the Generated Code

It's time to go look at the code that was generated from the template. This will give us a chance to see how this is all put together.

I'm going to assume you know a thing or two about programming. If you're completely new to programming entirely, then you're probably better served by learning some basics. Any language will work, but I recommend C#. If you don't know C# already (or want a refresher), you're in luck! I have a whole pile of tutorials that will teach you how to program in C#!

The template generates code in two files: Program.cs and Game1.cs. It is possible that Game1.cs is open in your editor already and you can see it, but if not, don't worry.

Start by opening both Program.cs and Game1.cs by double-clicking on them in the Solution Explorer on the right. (The Solution Explorer can be moved around, so if you don't see it on the right side, look around for a tree view elsewhere. If you're still not finding it, open it up by clicking on View > Solution Explorer. Then open the two .cs files from there.)

Program.cs

Let's start in Program.cs.

This is the code that launches your game—the entry point to your program.

using var game = new MyFirstGame.Game1();
game.Run();

This doesn't do a whole lot, but also doesn't need to. It simply makes a new instance of the class that is your main game and tells it to run.

You won't typically need to modify this file. It likely already does what you want it to do. But there's nothing dangerous or bad about modifying it if you feel it is the best place for some new bit of code to go.

Using Directives

The rest of this tutorial will look at the contents in Game1.cs.

This file is the meat of your game. In the short term, it is okay to add new code in here, but over time, you'll start making lots of other classes and files, and it won't all go into Game1.cs.

Furthermore, I typically recommend renaming Game1.cs and the Game1 class to something better. But I do often see that Game1 class hanging around in MonoGame projects for a very long time into a project's life. Right now, I'm not going to change mine for this particular tutorial, and I'll keep calling it "Game1," but that's partly because this tutorial isn't making any specific game. While "Game1" is a terrible name, there just isn't anything that is materially better here. But if you're making Tic-Tac-Toe, then perhaps the class could be renamed to TicTacToeGame and the file to TicTacToeGame.cs.

At any rate, the first thing you'll see in this file is a pile of using directives that look like this:

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

These using directives are just your typical C# using directives and give us convenient access to the three most common MonoGame namespaces.

It is notable that these all start with Microsoft.Xna instead of MonoGame. MonoGame's intent has been to be 100% source code compatible with XNA. MonoGame has been obligated to stick with the namespaces used in XNA to make that happen. That may not last forever in the future, as MonoGame seems to be leaning more toward becoming its own thing. (Besides, XNA has been retired since about 2013, so the compatibility is no longer nearly as valuable as it once was.)

The Namespace and Game1 Class

After the using directives, you'll find this code (with the guts cut out, because we'll look at that in a moment):

namespace MyFirstGame
{
    public class Game1 : Game
    {
        // ...
    }
}

This is, again, typical namespaces and class definitions. You are allowed to change this to a file-scoped namespace declaration if you want. To echo what I mentioned a moment ago, I recommend picking a better name than Game1 for your main game class.

The last bit here is that your new game class is derived from MonoGame's Game base class. This gets you a whole lot of functionality out of the box.

The most important bit is that this Game base class drives the game loop, working through some initialization steps (and later some teardown steps) and then iterating back and then cycling between updates, draws, and waiting.

Fields

Your main game class has two fields in it:

private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;

These are not used in the template, but you'll use both of these a fair bit in nearly all games that you make. _graphics gives you access to configuration of the graphics device and render settings, while _spriteBatch is a class that makes it easy to do 2D drawing. Even if you're making a 3D game, you'll still do a lot of 2D drawing.

We'll talk more about both of these later.

Constructor

The next chunk is the constructor:

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

I'm not going to belabor this one, because it is a fairly straightforward constructor. It simply gets some fields and properties initialized into a reasonable starting state, as you'd expect.

This is a place to put additional initialization for your game, but we'll see a couple of other places for this as well, depending on what you are doing.

The Initialize Method

The next method is the Initialize method:

protected override void Initialize()
{
    // TODO: Add your initialization logic here
 
    base.Initialize();
}

This method is called once after the constructor is called but before any other method in your Game1 class is called, and can be used to do some one-time initialization of your game after construction.

If you aren't putting anything specific in here, you can actually remove the whole thing. The only thing it does is call the version in the base class, which is what it will also do if you delete the whole thing. (And I've had a lot of games where this wasn't ever needed.) The only reason you might not delete this is that, once you do, it is out of your sight, and therefore, out of your mind, and you may not remember it is even around.

The LoadContent Method

The next method is LoadContent:

protected override void LoadContent()
{
    _spriteBatch = new SpriteBatch(GraphicsDevice);
 
    // TODO: use this.Content to load your game content here
}

This method is called after Initialize but before your game really gets running. You're allowed to load and unload content as your game runs. This is common as you progress from level to level, where each level needs different resources. For small games, you can get away with just loading everything once and calling it a day.

We'll do a lot of loading of content in the coming tutorials, but this is the main place where you'll do it.

The Update Method

The next method is the Update method:

protected override void Update(GameTime gameTime)
{
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
        Exit();
 
    // TODO: Add your update logic here
 
    base.Update(gameTime);
}

This method will get called a whole bunch, over and over as your game runs. If you want to know how long it has been since the last update, you can use the `gameTime` parameter to inspect it.

We'll be putting a lot of code in here as we go.

But the main rule of Update/Draw club is that you never put update code in the Draw method or drawing code in the Update method.

The only thing this method does initially is end the game if you push the Escape key on the keyboard or the Back button on the first connected gamepad.

We'll spend a lot of time in this method later on.

The Draw Method

The last method is the Draw method.

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);
 
    // TODO: Add your drawing code here
 
    base.Draw(gameTime);
}

We'll spend a lot of time in this method as well. But the main rule of Update/Draw club bears repeating: don't put update code in Draw or drawing code in Update.

This method is called over and over in the game loop, along with Update.

What's Next?

Going forward, we're going to make cooler and cooler games until you can make whatever game you can dream up. But that all started here when you made a game that drew a cornflower blue background.

In the next tutorial, we'll look at how MonoGame handles loading content, with its very own content pipeline.


Troubleshooting.png Having problems with this tutorial? Try the troubleshooting page!