Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

C# API 与 GDScript 的差异

这是C#和GDScript之间API差异的(不完整)列表.

一般差异

C# 基础 中所述,C#通常使用 PascalCase 而不是GDScript和C++中使用的 snake_case.

全局作用域

全局函数和某些常量必须移动到类中, 因为C#不允许在命名空间中声明它们. 大多数全局常量都被移动到它们自己的枚举中.

常量

在 C# 中,只有基本类型可以是常量。例如,TAU 常量被替换为 Mathf.Tau 常量,但是 Vector2.RIGHT 常量被替换为 Vector2.Right 只读属性。这与常量的行为类似,但不能用于一些上下文中,如 switch 语句。

全局枚举常量被移动到它们自己的枚举中。例如, ERR_* 常量被移动到 Error 枚举中。

特殊情况:

GDScript

C#

TYPE_*

Variant.Type 枚举

OP_*

Variant.Operator 枚举

数学函数

abs, acos , asin , atanatan2 这样的全局数学函数位于 Mathf 下, 名为 Abs , Acos, Asin , AtanAtan2. 常数 PI 可以通过 Mathf.Pi 获得.

C# 也提供了静态 System.MathSystem.MathF 类,其中可能包含其他有用的数学操作。

随机函数

rand_rangerand_seed 等全局随机函数位于 GD 下. 例如 GD.RandRange 以及 GD.RandSeed.

请考虑使用 System.Random ,如果你需要加密强度的随机性,使用 System.Security.Cryptography.RandomNumberGenerator

其他函数

许多其他全局函数,如 printvar_to_str ,位于 GD 下。例如: GD.PrintGD.VarToStr

例外情况:

GDScript

C#

weakref(obj)

GodotObject.WeakRef(obj)

instance_from_id(id)

GodotObject.InstanceFromId(id)

is_instance_id_valid(id)

GodotObject.IsInstanceIdValid(id)

is_instance_valid(obj)

GodotObject.IsInstanceValid(obj)

提示

有时候, 使用 using static 指令是很有用的. 该指令允许在不指定类名的情况下, 访问类的成员和嵌套类型.

示例:

using static Godot.GD;

public class Test
{
    static Test()
    {
        Print("Hello"); // Instead of GD.Print("Hello");
    }
}

完整的等效列表

Godot 全局作用域函数及其在 C# 中的等效函数列表:

GDScript

C#

abs

Mathf.Abs

absf

Mathf.Abs

absi

Mathf.Abs

acos

Mathf.Acos

acosh

Mathf.Acosh

angle_difference

Mathf.AngleDifference

asin

Mathf.Asin

asinh

Mathf.Asinh

atan

Mathf.Atan

atan2

Mathf.Atan2

atanh

Mathf.Atanh

bezier_derivative

Mathf.BezierDerivative

bezier_interpolate

Mathf.BezierInterpolate

bytes_to_var

GD.BytesToVar

bytes_to_var_with_objects

GD.BytesToVarWithObjects

ceil

Mathf.Ceil

ceilf

Mathf.Ceil

ceili

Mathf.CeilToInt

clamp

Mathf.Clamp

clampf

Mathf.Clamp

clampi

Mathf.Clamp

cos

Mathf.Cos

cosh

Mathf.Cosh

cubic_interpolate

Mathf.CubicInterpolate

cubic_interpolate_angle

Mathf.CubicInterpolateAngle

cubic_interpolate_angle_in_time

Mathf.CubicInterpolateInTime

cubic_interpolate_in_time

Mathf.CubicInterpolateAngleInTime

db_to_linear

Mathf.DbToLinear

deg_to_rad

Mathf.DegToRad

ease

Mathf.Ease

error_string

Error.ToString

exp

Mathf.Exp

floor

Mathf.Floor

floorf

Mathf.Floor

floori

Mathf.FloorToInt

fmod

operator %

fposmod

Mathf.PosMod

hash

GD.Hash

instance_from_id

GodotObject.InstanceFromId

inverse_lerp

Mathf.InverseLerp

is_equal_approx

Mathf.IsEqualApprox

is_finite

Mathf.IsFinite 或 float.IsFinitedouble.IsFinite

is_inf

Mathf.IsInf 或 float.IsInfinitydouble.IsInfinity

is_instance_id_valid

GodotObject.IsInstanceIdValid

is_instance_valid

GodotObject.IsInstanceValid

is_nan

Mathf.IsNaN 或 float.IsNaNdouble.IsNaN

is_same

operator == 或 object.ReferenceEquals

is_zero_approx

Mathf.IsZeroApprox

lerp

Mathf.Lerp

lerp_angle

Mathf.LerpAngle

lerpf

Mathf.Lerp

linear_to_db

Mathf.LinearToDb

log

Mathf.Log

max

Mathf.Max

maxf

Mathf.Max

maxi

Mathf.Max

min

Mathf.Min

minf

Mathf.Min

mini

Mathf.Min

move_toward

Mathf.MoveToward

nearest_po2

Mathf.NearestPo2

pingpong

Mathf.PingPong

posmod

Mathf.PosMod

pow

Mathf.Pow

print

GD.Print

print_rich

GD.PrintRich

print_verbose

使用 OS.IsStdoutVerbose 和 GD.Print

printerr

GD.PrintErr

printraw

GD.PrintRaw

prints

GD.PrintS

printt

GD.PrintT

push_error

GD.PushError

push_warning

GD.PushWarning

rad_to_deg

Mathf.RadToDeg

rand_from_seed

GD.RandFromSeed

randf

GD.Randf

randf_range

GD.RandRange

randfn

GD.Randfn

randi

GD.Randi

randi_range

GD.RandRange

randomize

GD.Randomize

remap

Mathf.Remap

rid_allocate_id

N/A

rid_from_int64

N/A

rotate_toward

Mathf.RotateToward

round

Mathf.Round

roundf

Mathf.Round

roundi

Mathf.RoundToInt

seed

GD.Seed

sign

Mathf.Sign

signf

Mathf.Sign

signi

Mathf.Sign

sin

Mathf.Sin

sinh

Mathf.Sinh

smoothstep

Mathf.SmoothStep

snapped

Mathf.Snapped

snappedf

Mathf.Snapped

snappedi

Mathf.Snapped

sqrt

Mathf.Sqrt

step_decimals

Mathf.StepDecimals

str

使用 $ string interpolation

str_to_var

GD.StrToVar

tan

Mathf.Tan

tanh

Mathf.Tanh

type_convert

Variant.As<T> or GD.Convert

type_string

Variant.Type.ToString

typeof

Variant.VariantType

var_to_bytes

GD.VarToBytes

var_to_bytes_with_objects

GD.VarToBytesWithObjects

var_to_str

GD.VarToStr

weakref

GodotObject.WeakRef

wrap

Mathf.Wrap

wrapf

Mathf.Wrap

wrapi

Mathf.Wrap

GDScript 实用函数与它们在 C# 中的等效函数列表:

GDScript

C#

assert

System.Diagnostics.Debug.Assert

char

使用显式转换: (char)65

convert

GD.Convert

dict_to_inst

N/A

get_stack

System.Environment.StackTrace

inst_to_dict

N/A

len

N/A

load

GD.Load

preload

N/A

print_debug

N/A

print_stack

GD.Print(System.Environment.StackTrace)

range

GD.Range 或 System.Linq.Enumerable.Range

type_exists

ClassDB.ClassExists(type)

preload 在 GDScript 中可用,在 C# 中不可用。请使用 GD.LoadResourceLoader.Load 替代。

@export 注解

使用 [Export] 特性替代 GDScript 的 @export 注解。该特性还可以接受 PropertyHinthintString 参数。默认值可以通过赋值来设置。

示例:

using Godot;

public partial class MyNode : Node
{
    [Export]
    private NodePath _nodePath;

    [Export]
    private string _name = "default";

    [Export(PropertyHint.Range, "0,100000,1000,or_greater")]
    private int _income;

    [Export(PropertyHint.File, "*.png,*.jpg")]
    private string _icon;
}

另见:C# 导出属性

signal 关键字

使用 [Signal] 特性声明信号,而不是使用 GDScript 中的 signal 关键字。这个特性应该用在一个 delegate 上,该 delegate 的名称将用于定义信号。这个 delegate 必须带有 EventHandler 后缀,一个 event 将在同名的类中生成,但不包含后缀,使用该事件的名称与 EmitSignal 配合使用。

[Signal]
delegate void MySignalEventHandler(string willSendAString);

另见: C# 信号 .

@onready 注解

GDScript 有一种能力,可以使用 @onready (参见: @onready 注解 )延迟成员变量的初始化,直到调用 ready 函数。例如:

@onready var my_label = get_node("MyLabel")

然而 C# 没有这个能力。为了达到同样的效果,你需要这样做。

private Label _myLabel;

public override void _Ready()
{
    _myLabel = GetNode<Label>("MyLabel");
}

单例

单例可以作为静态类使用, 而不是使用单例模式. 这是为了使代码不像使用 Instance 属性那样冗长.

示例:

Input.IsActionPressed("ui_down")

但是,在极少数情况下,这还不够。例如,你可能希望访问基类 GodotObject 中的成员,比如 Connect 。对于此类情况,我们提供了一个名为 Singleton 的静态属性,该属性返回单例实例。这个实例的类型是 GodotObject

示例:

Input.Singleton.JoyConnectionChanged += Input_JoyConnectionChanged;

字符串

使用 System.Stringstring )。大多数 Godot 的 String 方法都有与之等价的 System.String 方法,或者作为扩展方法由 StringExtensions 类提供。

示例:

string text = "Get up!";
string[] bigrams = text.Bigrams(); // ["Ge", "et", "t ", " u", "up", "p!"]

.NET 中的字符串是不可变的,因此所有操作字符串的方法不会修改原始字符串,而是返回一个经过修改的新字符串。为了避免创建多个字符串分配,考虑使用 StringBuilder

Godot 的 String 方法及其在 C# 中的等效方法列表:

GDScript

C#

begins_with

string.StartsWith

bigrams

StringExtensions.Bigrams

bin_to_int

StringExtensions.BinToInt

c_escape

StringExtensions.CEscape

c_unescape

StringExtensions.CUnescape

capitalize

StringExtensions.Capitalize

casecmp_to

StringExtensions.CasecmpTo 或 StringExtensions.CompareTo (考虑使用 string.Equalsstring.Compare

chr

N/A

contains

string.Contains

count

StringExtensions.Count (考虑使用 RegEx

countn

StringExtensions.CountN(考虑使用 RegEx

dedent

StringExtensions.Dedent

ends_with

string.EndsWith

erase

string.Remove (考虑使用 StringBuilder 来操作字符串)

find

StringExtensions.Find(考虑使用 string.IndexOfstring.IndexOfAny

findn

StringExtensions.FindN(考虑使用 string.IndexOfstring.IndexOfAny

format

使用 $ string interpolation

get_base_dir

StringExtensions.GetBaseDir

get_basename

StringExtensions.GetBaseName

get_extension

StringExtensions.GetExtension

get_file

StringExtensions.GetFile

get_slice

N/A

get_slice_count

N/A

get_slicec

N/A

hash

StringExtensions.Hash(除非你需要保证与 GDScript 中相同的行为,否则考虑使用 object.GetHashCode

hex_decode

StringExtensions.HexDecode(考虑使用 System.Convert.FromHexString

hex_to_int

StringExtensions.HexToInt(考虑使用 int.Parselong.Parse ,并使用 System.Globalization.NumberStyles.HexNumber

humanize_size

N/A

indent

StringExtensions.Indent

insert

string.Insert(考虑使用 StringBuilder 来操作字符串)

is_absolute_path

StringExtensions.IsAbsolutePath

is_empty

string.IsNullOrEmptystring.IsNullOrWhiteSpace

is_relative_path

StringExtensions.IsRelativePath

is_subsequence_of

StringExtensions.IsSubsequenceOf

is_subsequence_ofn

StringExtensions.IsSubsequenceOfN

is_valid_filename

StringExtensions.IsValidFileName

is_valid_float

StringExtensions.IsValidFloat(请考虑使用 float.TryParsedouble.TryParse

is_valid_hex_number

StringExtensions.IsValidHexNumber

is_valid_html_color

StringExtensions.IsValidHtmlColor

is_valid_identifier

StringExtensions.IsValidIdentifier

is_valid_int

StringExtensions.IsValidInt(请考虑使用 int.TryParselong.TryParse

is_valid_ip_address

StringExtensions.IsValidIPAddress

join

string.Join

json_escape

StringExtensions.JSONEscape

left

StringExtensions.Left(请考虑使用 string.Substringstring.AsSpan

length

string.Length

lpad

string.PadLeft

lstrip

string.TrimStart

match

StringExtensions.Match(请考虑使用 RegEx

matchn

StringExtensions.MatchN(请考虑使用 RegEx

md5_buffer

StringExtensions.Md5Buffer(请考虑使用 System.Security.Cryptography.MD5.HashData

md5_text

StringExtensions.Md5Text(请考虑使用 System.Security.Cryptography.MD5.HashData 和 StringExtensions.HexEncode)

naturalnocasecmp_to

N/A(请考虑使用 string.Equalsstring.Compare

nocasecmp_to

StringExtensions.NocasecmpTo 或 StringExtensions.CompareTo(请考虑使用 string.Equalsstring.Compare

num

float.ToStringdouble.ToString

num_int64

int.ToStringlong.ToString

num_scientific

float.ToStringdouble.ToString

num_uint64

uint.ToStringulong.ToString

pad_decimals

StringExtensions.PadDecimals

pad_zeros

StringExtensions.PadZeros

path_join

StringExtensions.PathJoin

repeat

请使用 string constructorStringBuilder

replace

string.ReplaceRegEx

replacen

StringExtensions.ReplaceN(请考虑使用 string.ReplaceRegEx

reverse

N/A

rfind

StringExtensions.RFind(请考虑使用 string.LastIndexOfstring.LastIndexOfAny

rfindn

StringExtensions.RFindN(请考虑使用 string.LastIndexOfstring.LastIndexOfAny

right

StringExtensions.Right(请考虑使用 string.Substringstring.AsSpan

rpad

string.PadRight

rsplit

N/A

rstrip

string.TrimEnd

sha1_buffer

StringExtensions.Sha1Buffer(请考虑使用 System.Security.Cryptography.SHA1.HashData

sha1_text

StringExtensions.Sha1Text(请考虑使用 System.Security.Cryptography.SHA1.HashData 和 StringExtensions.HexEncode)

sha256_buffer

StringExtensions.Sha256Buffer(请考虑使用 System.Security.Cryptography.SHA256.HashData

sha256_text

StringExtensions.Sha256Text(请考虑使用 System.Security.Cryptography.SHA256.HashData 和 StringExtensions.HexEncode)

similarity

StringExtensions.Similarity

simplify_path

StringExtensions.SimplifyPath

split

StringExtensions.Split(请考虑使用 string.Split

split_floats

StringExtensions.SplitFloat

strip_edges

StringExtensions.StripEdges(请考虑使用 string.Trimstring.TrimStartstring.TrimEnd

strip_escapes

StringExtensions.StripEscapes

substr

StringExtensions.Substr(请考虑使用 string.Substringstring.AsSpan

to_ascii_buffer

StringExtensions.ToAsciiBuffer(请考虑使用 System.Text.Encoding.ASCII.GetBytes

to_camel_case

StringExtensions.ToCamelCase

to_float

StringExtensions.ToFloat(请考虑使用 float.TryParsedouble.TryParse

to_int

StringExtensions.ToInt(请考虑使用 int.TryParselong.TryParse

to_lower

string.ToLower

to_pascal_case

StringExtensions.ToPascalCase

to_snake_case

StringExtensions.ToSnakeCase

to_upper

string.ToUpper

to_utf16_buffer

StringExtensions.ToUtf16Buffer(请考虑使用 System.Text.Encoding.UTF16.GetBytes

to_utf32_buffer

StringExtensions.ToUtf32Buffer(请考虑使用 System.Text.Encoding.UTF32.GetBytes

to_utf8_buffer

StringExtensions.ToUtf8Buffer(请考虑使用 System.Text.Encoding.UTF8.GetBytes

to_wchar_buffer

StringExtensions.ToUtf16Buffer in Windows and StringExtensions.ToUtf32Buffer in other platforms

trim_prefix

StringExtensions.TrimPrefix

trim_suffix

StringExtensions.TrimSuffix

unicode_at

string[int] 索引器

uri_decode

StringExtensions.URIDecode(请考虑使用 System.Uri.UnescapeDataString

uri_encode

StringExtensions.URIEncode(请考虑使用 System.Uri.EscapeDataString

validate_node_name

StringExtensions.ValidateNodeName

xml_escape

StringExtensions.XMLEscape

xml_unescape

StringExtensions.XMLUnescape

Godot PackedByteArray 的创建字符串方法,以及在 C# 中的等效方法列表:

GDScript

C#

get_string_from_ascii

StringExtensions.GetStringFromAscii(请考虑使用 System.Text.Encoding.ASCII.GetString

get_string_from_utf16

StringExtensions.GetStringFromUtf16(请考虑使用 System.Text.Encoding.UTF16.GetString

get_string_from_utf32

StringExtensions.GetStringFromUtf32(请考虑使用 System.Text.Encoding.UTF32.GetString

get_string_from_utf8

StringExtensions.GetStringFromUtf8(请考虑使用 System.Text.Encoding.UTF8.GetString

hex_encode

StringExtensions.HexEncode(请考虑使用 System.Convert.ToHexString

  • .NET 在 System.IO.Path 类下包含许多路径实用方法,用于处理非 Godot 路径(以 res://user:// 开头的路径)

节点路径

以下方法已转换为具有不同名称的属性:

GDScript

C#

is_empty()

IsEmpty

信号

下列方法已转换为属性, 其各自名称已被更改:

GDScript

C#

get_name()

Name

get_object()

Owner

Signal 类型实现了可等待模式,这意味着它可以与 await 关键字一起使用。请参阅: await 关键字

在 C# 中使用 Godot 信号的推荐方式不是使用 Signal 类型,而是使用生成的 C# 事件。请参阅: C# 信号

Callable

下列方法已转换为属性, 其各自名称已被更改:

GDScript

C#

get_object()

Target

get_method()

Method

当前 C# 支持 Callable 如果满足以下条件之一:

  • Callable 是使用 C# 的 Callable 类型创建的。

  • Callable 是引擎的 可调用体 的原始版本。不支持自定义的 Callable 。当以下任一条件成立时,一个 Callable 就是自定义的:

    • Callable 有绑定信息(用 bind/unbind 创建的 Callable 是不支持的)。

    • Callable 是通过 GDExtension API 从其他语言创建的。

一些方法,如 bindunbind ,没有实现,请使用 lambda 表达式代替:

string name = "John Doe";
Callable callable = Callable.From(() => SayHello(name));

void SayHello(string name)
{
    GD.Print($"Hello {name}");
}

lambda 表达式捕获了 name 变量,所以它可以绑定到 SayHello 方法。

RID

这种类型在 C# 中被命名为 Rid ,以遵循 .NET 的命名惯例。

下列方法已转换为属性, 其各自名称已被更改:

GDScript

C#

get_id()

Id

is_valid()

IsValid

Basis

结构体在 C# 中不能有无参数构造函数。因此 new Basis() 会将所有原始成员初始化为其默认值。使用 Basis.Identity 作为 GDScript 和 C++ 中的 Basis() 的等价物。

以下方法已转换为具有不同名称的属性:

GDScript

C#

get_scale()

Scale

Transform2D

结构在C#中不能有无参数构造函数, 因此 new Transform2D() 将所有原始成员初始化为其默认值. 请使用 Transform2D.Identity, 相当于GDScript和C++中的 Transform2D() .

下列方法已转换为属性, 其各自名称已被更改:

GDScript

C#

get_rotation()

Rotation

get_scale()

Scale

get_skew()

Skew

Transform3D

结构在 C# 中不能有无参构造函数。因此 new Transform3D() 会将所有原始成员初始化为其默认值。请使用 Transform3D.Identity 来代替 GDScript 和 C++ 中的 Transform3D()

下列方法已转换为属性, 其各自名称已被更改:

GDScript

C#

get_rotation()

Rotation

get_scale()

Scale

Rect2

以下字段已转换为名称 稍有 不同的属性:

GDScript

C#

end

End

以下方法已转换为具有不同名称的属性:

GDScript

C#

get_area()

Area

Rect2i

这种类型在 C# 中被命名为 Rect2I ,以遵循 .NET 的命名惯例。

以下字段已转换为名称 稍有 不同的属性:

GDScript

C#

end

End

以下方法已转换为具有不同名称的属性:

GDScript

C#

get_area()

Area

AABB

这种类型在 C# 中被命名为 Aabb ,以遵循 .NET 的命名惯例。

以下方法已转换为具有不同名称的属性:

GDScript

C#

get_volume()

Volume

Quaternion

结构在 C# 中不能有无参构造函数。因此 new Quaternion() 会将所有原始成员初始化为其默认值。请使用 Quaternion.Identity 来代替 GDScript 和 C++ 中的 Quaternion()

Projection

结构在 C# 中不能有无参构造函数。因此 new Projection() 会将所有原始成员初始化为其默认值。请使用 Projection.Identity 来代替 GDScript 和 C++ 中的 Projection()

Color

结构在 C# 中不能有无参构造函数。因此 new Color() 会将所有原始成员初始化为其默认值(这表示透明黑色)。请使用 Color.Black 来代替 GDScript 和 C++ 中的 Color()

全局的 Color8 方法可以用字节来构造一个 Color 类型,它是 Color 类型的一个静态方法。

Color 常量可以在 Colors 静态类中以只读属性的形式获取。

以下方法已转换为具有不同名称的属性:

GDScript

C#

get_luminance()

Luminance

以下方法已转换为具有不同名称的方法:

GDScript

C#

html(String)

FromHtml(ReadOnlySpan<char>)

以下方法改为使用构造函数:

GDScript

C#

hex(int)

Color(uint)

hex64(int)

Color(ulong)

数组

与紧缩数组等价的是 System.Array

另见 C# 中的紧缩数组

使用 Godot.Collections.Array 来表示无类型的 Variant 数组。 Godot.Collections.Array<T> 是对 Godot.Collections.Array 的类型安全封装。

另见: C# 中的数组

字典

Use Godot.Collections.Dictionary for an untyped Variant dictionary. Godot.Collections.Dictionary<TKey, TValue> is a type-safe wrapper around Godot.Collections.Dictionary.

另见: C# 中的字典

Variant

Godot.Variant 用于表示 Godot 的原生 Variant 类型。任何与 Variant 兼容的类型都可以与之相互转换。

另见: C# Variant

与其他脚本语言通信

跨语言脚本 中有详细解释。

await 关键字

类似于 GDScript 的 await 关键字,可以通过 C# 的 await 关键字 来实现。

C# 中的 await 关键字可以用于任何可等待的表达式。它通常用于类型为 TaskTask<TResult>ValueTaskValueTask<TResult> 的操作数。

表达式 t 如果满足以下条件之一,则可等待:

  • t 的编译时类型为 dynamic

  • t 有一个可访问的名为 GetAwaiter 的实例方法或扩展方法,没有参数和类型参数,返回类型为 A ,并且满足以下所有条件:

    • A 实现了接口 System.Runtime.CompilerServices.INotifyCompletion

    • A 有一个可访问、可读的实例属性 IsCompleted ,类型为 bool

    • A 有一个可访问的实例方法 GetResult ,没有参数和类型参数。

可以用 await 关键字和 GodotObject.ToSignal 实现 GDScript 中等待信号的等效操作。

示例:

public async Task SomeFunction()
{
    await ToSignal(timer, Timer.SignalName.Timeout);
    GD.Print("After timeout");
}