-
Notifications
You must be signed in to change notification settings - Fork 19
SampleImplementation
For this stage, we will duplicate the larger example from the Dear Imgui readme so you can see some of the inherent differences in Monogame from the parent project.
If you have not already configured your game for the MonoGame.ImGuiNet project, you should start with the Project Setup page and then come back here.
First, we must add the following 4 sections of code to the basic Game1.cs.
- Declare a new variable for the ImgGuiRenderer to the class variables of Game1.cs:
public class Game1 : Game
{
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
public static ImGuiRenderer GuiRenderer;- Instance the GuiRenderer in the Initialise method:
protected override void Initialize()
{
GuiRenderer = new ImGuiRenderer(this);
base.Initialize();
}- Rebuild the font atlas in the LoadContent method:
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
GuiRenderer.RebuildFontAtlas();
}- Call the layout methods after base.Draw in the Draw method:
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
base.Draw(gameTime);
GuiRenderer.BeforeLayout(gameTime);
GuiRenderer.AfterLayout();
}Think of these last two calls in the same way as MonoGame's _spriteBatch.Begin and _spriteBatch.End All of our actual drawing of Dear ImGui's elements will happen between these two lines.
Now we're ready to add our actual functional and informative elements to the Gui so we can do things. Our first tool will be very simple. Add the following two lines between GuiRenderer.BeforeLayout and GuiRenderer.AfterLayout:
ImGui.Begin("My First Tool");
ImGui.End();With those two lines, you should now be able to run the game and have a simple window that can be moved, resized and minimised as follows:

ImGui.Begin and ImGui.End can also be thought of in a similar manner to MonoGame's _spriteBatch.Begin and _spriteBatch.End - but everything inside them will "belong to that specific tool.
We will first add a menu and simple method of "closing" the tool.
To do so, you will need to create a new private bool _toolActive; to Game1.cs's class variables and initialise it to true. Then modify the code inside GuiRenderer.BeforeLayout and GuiRenderer.AfterLayout as follows:
if (_toolActive)
{
ImGui.Begin("My First Tool", ref _toolActive, ImGuiWindowFlags.MenuBar);
if (ImGui.BeginMenuBar())
{
if (ImGui.BeginMenu("File"))
{
if (ImGui.MenuItem("Open..", "Ctrl+O")) { /* Do stuff */ }
if (ImGui.MenuItem("Save", "Ctrl+S")) { /* Do stuff */ }
if (ImGui.MenuItem("Close", "Ctrl+W")) { _toolActive = false; }
ImGui.EndMenu();
}
ImGui.EndMenuBar();
}
ImGui.End();
}