Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

C# 基础

前言

警告

.NET support has been heavily modified between Godot 3 and 4. As such, you may still run into some issues, or find spots where the documentation could be improved.

Please report issues with C# in Godot on the engine GitHub page, and any documentation issues on the documentation GitHub page.

This page provides a brief introduction to C#, both what it is and how to use it in Godot. Afterwards, you may want to look at how to use specific features, read about the differences between the C# and the GDScript API, and (re)visit the Scripting section of the step-by-step tutorial.

C# is a high-level programming language developed by Microsoft. In Godot, it is implemented with .NET 6.0.

注意

Projects written in C# using Godot 4.x currently cannot be exported to Android, iOS and web platforms. To use C# on those platforms, use Godot 3 instead.

备注

不是 一个关于C#语言整体的全面教程. 如果你还不熟悉其语法或功能, 请参阅 Microsoft C #指南 或在其他地方寻找合适的介绍.

先决条件

Godot bundles the parts of .NET needed to run already compiled games. However, Godot does not bundle the tools required to build and compile games, such as MSBuild and the C# compiler. These are included in the .NET SDK, and need to be installed separately.

In summary, you must have installed the .NET SDK and the .NET-enabled version of Godot.

Download and install the latest stable version of the SDK from the .NET download page.

重要

如果您使用 64 位版本的 Godot,请务必安装 64 位版本的 SDK。

If you are building Godot from source, make sure to follow the steps to enable .NET support in your build as outlined in the Compiling with .NET page.

配置外部编辑器

C# support in Godot's built-in script editor is minimal. Consider using an external IDE or editor, such as Visual Studio Code or MonoDevelop. These provide autocompletion, debugging, and other useful features for C#. To select an external editor in Godot, click on Editor → Editor Settings and scroll down to Dotnet. Under Dotnet, click on Editor, and select your external editor of choice. Godot currently supports the following external editors:

  • Visual Studio 2019

  • Visual Studio 2022

  • Visual Studio Code

  • MonoDevelop

  • Mac版的Visual Studio

  • JetBrains Rider

关于如何配置外部编辑器, 请参见以下章节:

JetBrains Rider

阅读完 "预备知识" 部分, 就可以下载安装 JetBrains Rider .

在Godot的 Editor → Editor Settings 菜单中:

  • Set Dotnet -> Editor -> External Editor to JetBrains Rider.

在Rider中:

  • 设置 MSBuild version.NET Core .

  • 安装 Godot支持 插件.

Visual Studio Code

看完 "预备知识" 部分, 就可以下载安装 Visual Studio Code (又名VS Code).

在Godot的 Editor → Editor Settings 菜单中:

  • Set Dotnet -> Editor -> External Editor to Visual Studio Code.

在 Visual Studio Code 中:

  • 安装 C # 扩展.

备注

如果你使用的是 Linux,需要安装 Mono SDK <https://www.mono-project.com/download/stable/#download-lin> 才能使用 C# 工具插件。

To configure a project for debugging, you need a tasks.json and launch.json file in the .vscode folder with the necessary configuration. An example configuration can be found here . In the tasks.json file, make sure the program parameter points to your Godot executable, either by changing it to the path of the executable or by defining a GODOT4 environment variable that points to the executable. Now, when you start the debugger in Visual Studio Code, your Godot project will run.

备注

There is also a C# Tools for Godot Visual Studio Code extension, that is meant to make this setup easier and to provide further useful tools. But it is not yet updated to work with Godot 4.

Visual Studio (仅限Windows)

下载并安装最新版本的 Visual Studio . 如果你选择了正确的工作负载,Visual Studio将包含所需的SDK, 所以你不需要手动安装 "预先告知" 部分列出的内容.

While installing Visual Studio, select this workload:

  • .NET desktop development

在Godot的 Editor → Editor Settings 菜单中:

  • Set Dotnet -> Editor -> External Editor to Visual Studio.

接下来,你需要在这里从 GitHub 上下载 Godot Visual Studio 扩展。双击下载的文件,并按照安装过程进行安装。

备注

安装扩展后,可能不会出现在 Visual Studio 里调试游戏的选项。要启用调试,有一个针对 Visual Studio 2019 的变通方案。这个问题针对 Visual Studio 2022 有单独的工单

备注

如果你看到了类似“Unable to find package Godot.NET.Sdk”的错误,你的 NuGet 配置可能有问题,需要进行修复。

修复 NuGet 配置文件的简单方法就是重新生成一个。在文件浏览器窗口中前往 %AppData%\NuGet。将 NuGet.Config 文件重命名或删除。重新构建 Godot 项目时,就会自动用默认值创建该文件。

创建C#脚本

成功为Godot设置C#之后, 在场景的节点的上下文菜单中选择 附加脚本 时, 应该看到以下选项:

../../../_images/attachcsharpscript.webp

Note that while some specifics change, most concepts work the same when using C# for scripting. If you're new to Godot, you may want to follow the tutorials on 脚本语言 at this point. While some documentation pages still lack C# examples, most notions can be transferred from GDScript.

项目设置和工作流程

When you create the first C# script, Godot initializes the C# project files for your Godot project. This includes generating a C# solution (.sln) and a project file (.csproj), as well as some utility files and folders (.godot/mono). All of these but .godot/mono are important and should be committed to your version control system. Everything under .godot can be safely added to the ignore list of your VCS. When troubleshooting, it can sometimes help to delete the .godot/mono folder and let it regenerate.

示例

这是一个空白的C#脚本, 带有一些注释, 以演示其工作方式.

using Godot;

public partial class YourCustomClass : Node
{
    // Member variables here, example:
    private int _a = 2;
    private string _b = "textvar";

    public override void _Ready()
    {
        // Called every time the node is added to the scene.
        // Initialization here.
        GD.Print("Hello from C# to Godot :)");
    }

    public override void _Process(double delta)
    {
        // Called every frame. Delta is time since the last frame.
        // Update game logic here.
    }
}

As you can see, functions normally in global scope in GDScript like Godot's print function are available in the GD static class which is part of the Godot namespace. For a full list of methods in the GD class, see the class reference pages for @GDScript and @GlobalScope.

备注

Keep in mind that the class you wish to attach to your node should have the same name as the .cs file. Otherwise, you will get the following error:

"Cannot find class XXX for script res://XXX.cs"

C#和GDScript之间的一般差异

C#API使用 PascalCase 而不是GDScript / C++中使用的 snake_case . 在可能的情况下, 字段和getters/setters已转换为属性. 一般来说,C#Godot API一贯力求尽可能合理.

有关更多信息, 请参见 C# API 与 GDScript 的差异 页面.

警告

You need to (re)build the project assemblies whenever you want to see new exported variables or signals in the editor. This build can be manually triggered by clicking the word Build in the top right corner of the editor. You can also click MSBuild at the bottom of the editor window to reveal the MSBuild panel, then click the Build button to reveal a dropdown, then click the Build Solution option.

你还需要重新构建项目集, 以应用 "工具" 脚本中的更改.

目前的陷阱和已知问题

As C# support is quite new in Godot, there are some growing pains and things that need to be ironed out. Below is a list of the most important issues you should be aware of when diving into C# in Godot, but if in doubt, also take a look over the official issue tracker for .NET issues.

  • 编写编辑器插件是可能的, 但是目前相当复杂.

  • 热重载时, 当前状态不被保存和恢复, 导出变量除外.

  • 附加C#脚本需要引用一个类, 该类名需要匹配其文件名.

  • There are some methods such as Get()/Set(), Call()/CallDeferred() and signal connection method Connect() that rely on Godot's snake_case API naming conventions. So when using e.g. CallDeferred("AddChild"), AddChild will not work because the API is expecting the original snake_case version add_child. However, you can use any custom properties or methods without this limitation. Prefer using the exposed StringName in the PropertyName, MethodName and SignalName to avoid extra StringName allocations and worrying about snake_case naming.

As of Godot 4.0, exporting .NET projects is supported for desktop platforms (Linux, Windows and macOS). Other platforms will gain support in future 4.x releases.

Common pitfalls

You might encounter the following error when trying to modify some values in Godot objects, e.g. when trying to change the X coordinate of a Node2D:

public partial class MyNode2D : Node2D
{
    public override _Ready()
    {
        Position.X = 100.0f;
        // CS1612: Cannot modify the return value of 'Node2D.Position' because
        // it is not a variable.
    }
}

This is perfectly normal. Structs (in this example, a Vector2) in C# are copied on assignment, meaning that when you retrieve such an object from a property or an indexer, you get a copy of it, not the object itself. Modifying said copy without reassigning it afterwards won't achieve anything.

The workaround is simple: retrieve the entire struct, modify the value you want to modify, and reassign the property.

var newPosition = Position;
newPosition.X = 100.0f;
Position = newPosition;

Since C# 10, it is also possible to use with expressions on structs, allowing you to do the same thing in a single line.

Position = Position with { X = 100.0f };

You can read more about this error on the C# language reference.

在Godot中C#的性能

According to some preliminary benchmarks, the performance of C# in Godot — while generally in the same order of magnitude — is roughly ~4× that of GDScript in some naive cases. C++ is still a little faster; the specifics are going to vary according to your use case. GDScript is likely fast enough for most general scripting workloads.

Most properties of Godot C# objects that are based on GodotObject (e.g. any Node like Control or Node3D like Camera3D) require native (interop) calls as they talk to Godot's C++ core. Consider assigning values of such properties into a local variable if you need to modify or read them multiple times at a single code location:

using Godot;

public partial class YourCustomClass : Node3D
{
    private void ExpensiveReposition()
    {
        for (var i = 0; i < 10; i++)
        {
            // Position is read and set 10 times which incurs native interop.
            // Furthermore the object is repositioned 10 times in 3D space which
            // takes additional time.
            Position += new Vector3(i, i);
        }
    }

    private void Reposition()
    {
        // A variable is used to avoid native interop for Position on every loop.
        var newPosition = Position;
        for (var i = 0; i < 10; i++)
        {
            newPosition += new Vector3(i, i);
        }
        // Setting Position only once avoids native interop and repositioning in 3D space.
        Position = newPosition;
    }
}

Passing raw arrays (such as byte[]) or string to Godot's C# API requires marshalling which is comparatively pricey.

The implicit conversion from string to NodePath or StringName incur both the native interop and marshalling costs as the string has to be marshalled and passed to the respective native constructor.

在Godot中使用NuGet包

NuGet 包可以与Godot一起安装和使用, 就像任何C#项目一样. 许多IDE都可以直接添加软件包. 也可以通过在项目根目录下的 .csproj 文件中添加软件包引用来手动添加它们:

    <ItemGroup>
        <PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
    </ItemGroup>
    ...
</Project>

从Godot 3.2.3开始,Godot在下次构建项目时自动下载并设置新添加的NuGet包。

分析 C# 代码

The following tools may be used for performance and memory profiling of your managed code:

  • JetBrains Rider with dotTrace/dotMemory plugin.

  • Standalone JetBrains dotTrace/dotMemory.

  • Visual Studio.

Profiling managed and unmanaged code at once is possible with both JetBrains tools and Visual Studio, but limited to Windows.