You are on page 1of 16

The Ultimate Godot C# Setup Guide https://giulianob.svbtle.

com/godot-csharp-setup

GIULIANOB

NOVEMBER 10, 2019

The Ultimate Godot C# Setup


Guide
Update: ince posting this article, a new VCode extension has been
released which ma simplif some of the steps below. I have been using
Rider instead of VCode so I have not had a chance to tr it out first hand
and update this article with the new information.

There are a few different guides out there for setting up Godot but I feel like
man don’t give ou all of the nitt gritt details needed to get a great
workflow. This guide is a bit long but it will set ou up with the following:

1. Run our game right from VCode.

2. Breakpoint debugging in VCode.

3. Crash logs when ou share our game.

4. Advanced code analsis/automated refactoring with Roslnator. For those


familiar with Resharper this is an open source alternative that supports
VCode.

I have tested this setup on Windows and Linux. If ou have an issues on
other platforms message me on discord @giulianob#9552. If ou’re looking
for just a template, head on over to the sample Github repo.

tep 1) Install VCode

Download the latest version of VCode from the official website and
complete the installation.
148
KUDOS

1 sur 16 24/10/2020 à 02:55


The Ultimate Godot C# Setup Guide https://giulianob.svbtle.com/godot-csharp-setup

Windows users will also need to download the NuGet command line utilit.
ave the nuget.exe to a director ou will remember for example c:\bin
\nuget.exe .

tep 2) Download Godot

Download the latest version of Godot with Mono and extract it to a director
of our choice.

If ou’re on Windows then install the Visual tudio Build Tools. For other
platforms, install the Mono DK.

tep 3) Configure Godot Project

tart up Godot and create a new project or open our existing project.

There are a few settings we should change to work with VCode and
improve our workflow.

1. Go to Editor menu > Editor ettings

2. Under Mono > Builds

Build Tool: elect either “MBuild (V Build Tools)” if on Windows or


“MBuild (Mono)” for other platforms.

3. Under Mono > Editor

External Editor: Visual tudio Code

4. Under Text Editor > Files

Open Dominant cript On cene Change: Uncheck

5. Close the editor settings dialog

6. Go to Project menu > Project ettings

7. Under Logging > File Logging


148
Enable File Logging: Check. This will make it easier to track down certain
KUDOS

2 sur 16 24/10/2020 à 02:55


The Ultimate Godot C# Setup Guide https://giulianob.svbtle.com/godot-csharp-setup

errors that crash our game unexpectedl. Feel free to lower the “Max
Log Files” setting.

8. Under Mono > Debugger Agent

Port: 23685

Wait Timeout: 3000

tep 4) Install MonoDebuggerQM Addon

This is an addon that gives us a shortcut to the “Mono > Debugger Agent >
Wait For Debugger” setting. We’ll need to toggle this setting whenever we
would like to perform a debugging session.

1. Download the latest release of MonoDebuggerQM.

2. Extract the zip to the addons folder of our project. For example if our
project is located at c:\myproject then ou should have a c:\myproject
\addons\MonoDebuggerQM-1.0.1\ director after extracting the zip.

3. Go to Project menu > Project ettings > Plugins and change the Status of the
MonoDebugger plugin to Active . If ou don’t see the plugin make sure ou
extracted it to the right location.

tep 5) Configure C# Project

Let’s create our initial scene. Just create a scene with a simple Node2D or
anthing ou like. Click Play or press F5 and make sure the game runs.

Now let’s start setting up the C# project.

1. Right click on our scene root and click Attach Script

2. Change the Language to C# and click Create.

After this happens a new option is available to us that we should change.

1. Go to Project menu > Project ettings 148


KUDOS

3 sur 16 24/10/2020 à 02:55


The Ultimate Godot C# Setup Guide https://giulianob.svbtle.com/godot-csharp-setup

2. Under Mono > Project

Auto Update Project: Uncheck. This will make it so Godot doesn’t


automaticall add or remove files from our csproj. It often fails to do it
correctl so we’ll do it in a simpler wa.

tep 6) Configure VCode

VCode should have opened when we created our script, if it didn’t, just
double click on our script in the FileSystem view or click on the script
icon on our root node.

1. Go to the Extensions tab on the left hand side.

2. Install the following extensions:

C# (b Microsoft)

Mono Debug (b Microsoft)

tep 7) Configure csproj File

Now let’s configure our csproj file to include some extra goodies.

1. Open our .csproj file. If our project is named MGodotGame then the file
will be called MyGodotGame.csproj .

2. Under the first <PropertyGroup> change the following line

<Configuration Condition=" '$(Configuration)' == ''


">Debug</Configuration>

to

<Configuration Condition=" '$(Configuration)' == ''


">Tools</Configuration>

This is technicall not required but if ou ever build our own addons ou
will not receive Intellisense unless ou change the project default to Tools
148
KUDOS

4 sur 16 24/10/2020 à 02:55


The Ultimate Godot C# Setup Guide https://giulianob.svbtle.com/godot-csharp-setup

instead of Debug like we did above.

1. Add the following lines after the <Configuration .. line we just edited
above:

<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<LangVersion>7.3</LangVersion>

This will enable some newer C# features that are not available in the default
settings of the csproj file.

1. Find the last <ItemGroup> which should contain the .cs file ou created.
For example mine is:

<ItemGroup>
<Compile Include="Default.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>

change it to

<ItemGroup>
<Compile Include="**\*.cs" />
</ItemGroup>

This option configures our project to build ever .cs file it finds and gets
around that unreliable setting we disabled earlier to auto update the project
file.

You can view m full csproj for reference on Github.

witch back to Godot and make sure ou can still run our game. If ou get
an Godot editor crashes now or in the future tr deleting our .mono
director.

tep 8) Configure VCode Launching/Debugging

Let’s configure the abilit to run our game right from VCode.
148
KUDOS

5 sur 16 24/10/2020 à 02:55


The Ultimate Godot C# Setup Guide https://giulianob.svbtle.com/godot-csharp-setup

1. In VCode, click on Debug menu > Open Configurations

2. If ou don’t et have a launch.json it will ask ou to choose a template.
Choose anthing, we’ll be replacing the contents.

3. Replace the contents of the launch.json file with this one from Github. I’ll
explain this file in more detail later.

Windows Users: Replace the path to the Godot .exe to wherever ou
have Godot installed.

Linux Users: Replace the path to the Godot .exe with godot-mono or
wherever ou have Godot installed.

4. Click on Terminal menu > Configure Tasks…

5. Once again if ou don’t have a tasks.json et defined then choose to create
a new one.

6. Replace the contents of the tasks.json file with this one from Github.

Windows Users: Replace the location of nuget.exe with wherever ou


saved it from step 1. The location to MsBuild.exe ma need to be
updated as well if ou have installed a different version of Build tools for
Visual tudio.

Linux Users: Just simpl use msbuild and nuget for the command.
The should be installed in our /usr/local/bin director.

7. Open our workspace settings b pressing Ctrl+Shift+P (to open the


command palette) and tping >Preferences> Open Workspace Settings
then add the following to our settings.json

{
"mono-debug.exceptionOptions": {
"System.ArithmeticException": "always",
"System.ArrayTypeMismatchException": "always",
"System.DivideByZeroException": "always",
"System.Exception": "always",
"System.IndexOutOfRangeException": "always",
148
"System.InvalidCastException": "always", KUDOS

6 sur 16 24/10/2020 à 02:55


The Ultimate Godot C# Setup Guide https://giulianob.svbtle.com/godot-csharp-setup

"System.NullReferenceException": "always",
"System.OutOfMemoryException": "always",
"System.OverflowException": "always",
"System.StackOverflowException": "always",
"System.SystemException": "always",
"System.TypeInitializationException": "always"
}
}

These settings will make sure that the debugger pauses if ou receive an
exceptions in our game. Tpicall the game will just crash and ou ma not
even get a stacktrace which makes it extremel difficult to debug.

1. Click on the Debug icon on the left hand menu bar and change the Debug
configuration to Run and Attach

2. witch back to Godot for just a second and check the “Wait for Debugger”
option on the top-right Debugger menu that was added b the 148
KUDOS

7 sur 16 24/10/2020 à 02:55


The Ultimate Godot C# Setup Guide https://giulianob.svbtle.com/godot-csharp-setup

MonoDebugger addon.

We’re all set up and we should be able to run our project right from
VCode!

Open our main C# file and add the following code

public override void _Ready()


{
var name = "Godot";
GD.PrintS("Hello", name);
}

Add a breakpoint b clicking on the margin or pressing F9 on the print line.


tart the project b hitting the Start Debugging pla button or F5 . Your
code should stop at our breakpoint, for example: 148
KUDOS

8 sur 16 24/10/2020 à 02:55


The Ultimate Godot C# Setup Guide https://giulianob.svbtle.com/godot-csharp-setup

You can see on the left hand side all of our local variables. You can add
other variables to watch in the Watch window or use the Debug Console.

To see the output of our code, ou will need to switch the Debug Console
to the Run configuration.

148
KUDOS

9 sur 16 24/10/2020 à 02:55


The Ultimate Godot C# Setup Guide https://giulianob.svbtle.com/godot-csharp-setup

Basicall what is happening is that we have three different configurations in


the launch.json .

1. Run : tarts the Godot editor from VCode

2. Attach : tarts the Mono debugger in VCode. The debugger listens for
connections that our game establishes when ou have the Wait For
Debugger option enabled in Godot.

3. Run and Attach : This will run the two configurations above to both start the
debugger and our game.

We have to switch between the two configurations to see the output


because we are actuall running both the Run and the Attach task at the
same time. If anone has a better solution for this please let me know!

Now to stop debugging ou have to either click the top button twice or
press Shift+F5 twice. If ou just tr to close the game ou will notice that it
just freezes.

Antime ou switch back to Godot and wish to run the project from Godot
itself then ou have the following options.

Option 1) Disable the “Wait for Debugger” option otherwise our game will run
148
for a few seconds then quit because it cannot connect to the debugger. You
KUDOS

10 sur 16 24/10/2020 à 02:55


The Ultimate Godot C# Setup Guide https://giulianob.svbtle.com/godot-csharp-setup

will get a socket timeout error.

Option 2) Change VCode to use the “Attach” task, hit F5 , then run Godot so
it can attach to the debugger with the “Wait for Debugger” option enabled. If
ou do this, ou will need to start the VCode debugger ever time ou restart
our game in Godot. I tpicall just disable the “Wait for Debugger” option if I’m
working within Godot and enable when in VCode.

tep 9) Install Roslnator (Optional)

Roslnator is an open source static analsis tool that can also perform some
automatic code fixes. If ou have experience with Resharper it’s an open
source alternative that has much better performance.

To install Roslnator:

1. Open our csproj file and add the following: In the first <PropertyGroup>
add

<CodeAnalysisRuleSet>roslynator.ruleset</CodeAnalysisRuleSet>

Then add a new <ItemGroup> with the following

<ItemGroup>
<PackageReference Include="Roslynator.Analyzers">
<Version>2.2.0</Version>
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers;
buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

At the time of this post Roslnator is at version 2.2.0 but feel free to install a
newer version if available.

You can see m full csproj file for reference.

1. Create a new file in the root of our project called roslynator.ruleset . I


recommend adding the following content in this file:
148
KUDOS

11 sur 16 24/10/2020 à 02:55


The Ultimate Godot C# Setup Guide https://giulianob.svbtle.com/godot-csharp-setup

<?xml version="1.0" encoding="utf-8"?>


<RuleSet Name="Rules for Project" ToolsVersion="15.0">
<Rules AnalyzerId="Microsoft.CodeAnalysis.CSharp.Features"
RuleNamespace="Microsoft.CodeAnalysis.CSharp.Features">
<Rule Id="IDE0060" Action="None" />
<Rule Id="IDE0005" Action="Info" />
<Rule Id="IDE0051" Action="None" />
<Rule Id="IDE0004" Action="Info" />
<Rule Id="RCS1129" Action="None" />
<Rule Id="RCS1074" Action="Info" />
</Rules>
<Rules AnalyzerId="Roslynator.CSharp.Analyzers"
RuleNamespace="Roslynator.CSharp.Analyzers">
<Rule Id="RCS1090" Action="None" />
<Rule Id="RCS1079" Action="None" />
<Rule Id="RCS1171" Action="None" />
<Rule Id="RCS1036" Action="None" />
<Rule Id="RCS1037" Action="None" />
<Rule Id="RCS1124" Action="None" />
<Rule Id="RCS1096" Action="None" />
</Rules>
</RuleSet>

This file defines some overrides to the default rules. For example, ou ma
not like some of the warnings Roslnator gives ou. The file above are some
rules that I personall disable or lower the severit to Info.

You can start with a blank ruleset (just make sure ou have the root
RuleSet element) and add exceptions as needed. You can view the full set
of analzers on the Roslnator project.

1. Open our workspace settings b pressing Ctrl+Shift+P and tping


>Preferences: Open Workspace Settings then add the following setting
{ "omnisharp.enableRoslynAnalyzers": true }

2. Perform a nuget restore b pressing Ctrl+Shift+P , tping >Tasks: Run


Tasks , and choosing the nugetrestore task. If ou have an errors make
sure that our nuget.exe is configured correctl in the
.vscode/tasks.json file. You can also run this on the command line b
executing nuget.exe restore in our project root.

3. Reload VCode.
148
KUDOS

12 sur 16 24/10/2020 à 02:55


The Ultimate Godot C# Setup Guide https://giulianob.svbtle.com/godot-csharp-setup

If we now tpe some code that fails one of the static analsis rules we will
receive a warning. For example

We can access the quick-fix menu b putting the cursor over one of the
issues and either clicking the lightbulb icon or pressing Ctrl+.

I’ve gone ahead and applied all of the automatic code fixes

148
KUDOS

13 sur 16 24/10/2020 à 02:55


The Ultimate Godot C# Setup Guide https://giulianob.svbtle.com/godot-csharp-setup

You can also access quite a few automated refactorings b pressing the
same shortcut even when there isn’t a warning. For example given the
following code

We can perform an automated refactoring if we focus on the if statement

148
KUDOS

14 sur 16 24/10/2020 à 02:55


The Ultimate Godot C# Setup Guide https://giulianob.svbtle.com/godot-csharp-setup

which will change this to a ternar operator

You can actuall keep going and it will offer to inline the offset .

tep 10) Add Unhandled Exception Handler (Optional)

There are times where our game can crash during start up, we enabled
pausing on exceptions in an earlier step which means the debugger will
stop whenever there’s an exception. However, it’s possible that once ou
export a release version of our project ou have some exceptions that ou
need to debug. That’s wh we enabled the file logging option in Godot in
the beginning of this tutorial. File logging will log all of our game’s
GD.Print statements in a file located at %APPDATA\Roaming\Godot
\app_userdata\YourProjectName . However, Godot b default will not log
exceptions thrown from our application so we have to do this ourselves b
adding the following code at our main scene cs file.

using System;
using Godot;

namespace SampleProject
{
public class Node : Node2D
{
public override void _Ready()
{
AppDomain.CurrentDomain.UnhandledException +=
UnhandledExceptionHandler;
}
148
KUDOS

15 sur 16 24/10/2020 à 02:55


The Ultimate Godot C# Setup Guide https://giulianob.svbtle.com/godot-csharp-setup

private void UnhandledExceptionHandler(object sender,


UnhandledExceptionEventArgs e)
{
GD.PrintS($"Got unhandled exception {e.ExceptionObject}");
GD.PrintErr("Quitting due to exception");
}
}
}

Now whenever our game throws an exception ou will be guaranteed to


have the error logged in the file. Again this is mainl useful when ou start
sharing our game with others and need them to send ou the crash logs.

That’s it!
I hope everthing here made sense. If ou need an help join the official
Godot #csharp channel on Discord and feel free to message me on Discord
at giulianob#9552.

You can find a sample project over at Github with all of the configurations
complete.

148 KUDOS

GIULIANOB @giuliano_b

SVBTLE

Terms • Privac • Promise

148
KUDOS

16 sur 16 24/10/2020 à 02:55

You might also like