With all the documentation you'll read for XNA, there will be one differentiating factor and that is the content pipeline.
The Content Pipeline can be a pain in the ass but it's overall very helpful as it nicely
packages content for the game in the Content
folder.
This tutorial will show you how to import a texture and load it in the game.
This tutorial assumes you have MonoGame installed for Visual Studio, it can be downloaded here.
This will install the Pipeline tool as well as Visual Studio tools for working with MonoGame.
For this tutorial, we will be adding a texture. Firstly, go to the project in Visual Studio and
right click the Content
folder; opening the folder in your file explorer.
You'll see there's a Content.mgcb
file, this is your pipeline file.
Double clicking the file will open the Content Pipeline tool. This tool is used for managing all
the assets of the game and building a content file for the game to work with.
Right clicking a folder, you'll see the option to Add Existing Item
. This is your friend, as
all the hard work is done by the tool. Ensure you select to copy the file into the working
directory.
Once you have added an image click the build icon at the top of the window to build the solution. After the build, your content has been taken account for and you can now use it in game. One thing that makes it very easy to work with content is by right clicking a file and selecting "Copy Asset Path" as this is the path you'll be using in-game.
To load the Texture in game you need to use Content.Load<T>
, this is an extension of the
Game
object so you will need to inherit it if you wish to use it outside of the LoadContent
void in Game1
.
Assuming you have access to Content, the only parameters required are:
T
: The datatype you're loading- In this case that's
Texture2D
as we're loading an image file and treating it as a texture
- In this case that's
- The filename
- Use the value from
Copy Asset Path
for this
- Use the value from
So for example, loading a texture named test_background.png
and passing it to a sprite object
would look like (assuming we have a public Sprite called _background:
Texture2D backgroundTexture = Content.Load<Texture2D>("Sprites/test_background");
_background = new Sprite(backgroundTexture, 1, 1, 0, 0);
or better yet:
_background = new Sprite(Content.Load<Texture2D>("Sprites/test_background"), 1, 1, 0, 0);
For bonus points, add these to your Update
and Draw
methods respectively:
_background.Update();
_background.Draw(spriteBatch);