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, AtanAtan2PI 常數則為 Mathf.Pi

C# 也提供靜態 System.MathSystem.MathF 類,它們可能包含其他有用的數學運算。

隨機數函式

隨機數全域函式,如 rand_rangerand_seed ,都放在 GD 底下。如: GD.RandRangeGD.RandSeed

考慮使用“System.Random”,或者,如果您需要加密的強隨機性,則使用“System.Security.Cryptography.RandomNumberGenerator”。

其他函式

許多其他的全域函式,如 printvar2str 都放在 GD 底下。如 GD.PrintGD.Var2Str

例外:

GDScript

C#

weakref(obj)

Object.WeakRef(obj)

is_instance_valid(obj)

Object.IsInstanceValid(obj)

is_instance_valid(obj)

Object.IsInstanceValid(obj)

is_instance_valid(obj)

Object.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 or float.IsFinite or double.IsFinite

is_inf

Mathf.IsInf or float.IsInfinity or double.IsInfinity

is_instance_id_valid

GodotObject.IsInstanceIdValid

is_instance_valid

GodotObject.IsInstanceValid

is_nan

Mathf.IsNaN or float.IsNaN or double.IsNaN

is_same

operator == or 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

最大值

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

Use OS.IsStdoutVerbose and 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

Use $ 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

List of GDScript utility functions and their equivalent in C#:

GDScript

C#

assert

System.Diagnostics.Debug.Assert

char

Use explicit conversion: (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 or System.Linq.Enumerable.Range

type_exists

ClassDB.ClassExists(type)

在 GDScript 中可用的 preload 無法於 C# 中使用。請使用 GD.LoadResourceLoader.Load 代替。

匯出選項

使用 [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_sharp_signals

訊號關鍵字

使用 [Signal] 屬性來取代 GDScript 中的 signal 關鍵字宣告訊號。這個屬性也可以用在 **delegate`` 上,其名稱簽章會用來定義訊號。

[Signal]
delegate void MySignalEventHandler(string willSendAString);

參見 c_sharp_signals

@onready 註釋

GDScript能夠推遲成員變數的初始化, 直到用 onready 呼叫ready函式(參見 doc_gdscript_onready_keyword ). 例如:

@onready var my_label = get_node("MyLabel")

然而C#沒有這個能力. 為了達到同樣的效果, 你需要這樣做.

private Label _myLabel;

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

單例

單例為靜態類別,而不是使用單例模式。這樣可以讓程式碼比起使用 Instance 屬性來得簡單。

範例:

Input.IsActionPressed("ui_down")

但,在某些罕見情況下,這樣還不夠。如,我們可能需要存取基礎型別 Godot.Object 中的成員,如 Connect 。這種情況下,可以使用一個靜態屬性,名為 Singleton ,這個屬性會回傳單例實體。該實體的型別為 Godot.Object

範例:

Input.Singleton.JoyConnectionChanged += Input_JoyConnectionChanged;

字串

使用 System.String (string) 。大多數 Godot 的字串方法都由 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

首字母大寫

StringExtensions.Capitalize

casecmp_to

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

chr

N/A

continue

建立內容

數量

StringExtensions.Count(考慮使用 RegEx

數量

StringExtensions.CountN(考慮使用 RegEx

dedent

StringExtensions.Dedent

ends_with

string.EndsWith

攝影機

string.Remove (考慮使用 StringBuilder 來操作字串)

find

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

findn

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

格式

Use $ 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(考慮使用 object.GetHashCode 除非您需要保證與 GDScript 中相同的行為)

hex_decode

StringExtensions.HexDecode(考慮使用`System.Convert.FromHexString`_)

hex_to_int

StringExtensions.HexToInt(考慮將 int.Parselong.ParseSystem.Globalization.NumberStyles.HexNumber 一起使用)

humanize_size

N/A

索引

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

識別項

StringExtensions.IsValidIdentifier

is_valid_int

StringExtensions.IsValidInt(請考慮使用 int.TryParselong.TryParse

is_valid_ip_address

StringExtensions.IsValidIPAddress

join

字串

json_escape

StringExtensions.JSONEscape

left

StringExtensions.Left(請考慮使用 string.Substringstring.AsSpan

每行字數限制

每行字數限制

lpad

string.PadLeft

字串

string.TrimStart

match

StringExtensions.Match(請考慮使用 RegEx

match

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

重覆

請使用 string constructorStringBuilder

取代

string.ReplaceRegEx

取代

StringExtensions.ReplaceN(請考慮使用 string.ReplaceRegEx

reverse

N/A

rfind

StringExtensions.RFind(請考慮使用 string.LastIndexOfstring.LastIndexOfAny

rfindn

StringExtensions.RFindN(請考慮使用 string.LastIndexOfstring.LastIndexOfAny

光照

StringExtensions.Right(請考慮使用 string.Substringstring.AsSpan

rpad

string.PadRight

rsplit

N/A

字串

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

浮點數

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

使用空白字元

StringExtensions.URIEncode(考慮使用`System.Uri.EscapeDataString`_)

validate_node_name

StringExtensions.ValidateNodeName

xml_escape

StringExtensions.XMLEscape

xml_unescape

StringExtensions.XMLUnescape

用於建立 String 的 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://」開頭的路徑時使用) `)

NodePath

下列方法轉換成了名稱不同的屬性:

GDScript

C#

center()

IsEmpty

訊號

下列各個方法皆轉換為屬性並更改其名稱:

GDScript

C#

get_area()

Name

get_area()

Owner

“Signal” 型別實作了可等待模式,這意味著它可以與“await” 關鍵字一起使用。請參閱:ref:doc_c_sharp_differences_await

在 C# 中使用 Godot 訊號的建議方法是使用產生的 C# 事件,而不是使用「Signal」型別。請參閱:ref:doc_c_sharp_signals

Call 呼叫

下列各個方法皆轉換為屬性並更改其名稱:

GDScript

C#

get_area()

目標

get_method()

Method

目前,如果滿足以下條件之一,C# 支援「Callable」:

  • Callable 是使用 C# Callable 型別建立的。

  • “回呼函式”是引擎“回呼函式”的基本版本。不支援自定義「可調用」 。當以下任何一項成立時,「回呼函式」是自定義的:

    • “回呼函式”具有綁定資訊(不支援使用“綁定”/“取消綁定”創建的“回呼函式”)。

    • 「Callable」 是透過 GDExtension API 從其他語言建立的。

有些方法如“bind”和“unbind”沒有實作,請使用lambdas代替:

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

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

lambda 捕獲“name”變量,以便將其綁定到“SayHello”方法。

RID

在這個專案中,我們會遵守 Godot 的命名慣例。

下列各個方法皆轉換為屬性並更改其名稱:

GDScript

C#

get_area()

Id

is_instance_valid(obj)

IsValid

基礎

在 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_scale()

Skew

Transform3D

在 C# 中,結構為無參數的建置函式。因此,new Transform2D() 會初始化所有原始成員並設為預設值。請使用 Transform2D.Identity 來達成與 GDScript 或 C++ 中 Transform2D() 同等的效果。

下列各個方法皆轉換為屬性並更改其名稱:

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

在這個專案中,我們會遵守 Godot 的命名慣例。

下列方法轉換成了名稱不同的屬性:

GDScript

C#

get_scale()

Volume

四元數

在 C# 中,結構為無參數的建置函式。因此,new Quat() 會初始化所有原始成員並設為預設值。請使用 Quat.Identity 來達到與 GDScript 或 C++ 中 Quat() 同等的效果。

投影

在 C# 中,結構為無參數的建置函式。因此,new Quat() 會初始化所有原始成員並設為預設值。請使用 Quat.Identity 來達到與 GDScript 或 C++ 中 Quat() 同等的效果。

顏色

在 C# 中,結構為無參數的建置函式。因此,new Quat() 會初始化所有原始成員並設為預設值。請使用 Quat.Identity 來達到與 GDScript 或 C++ 中 Quat() 同等的效果。

從位元組建構 Color 的全域「Color8」方法可用作 Color 型別中的靜態方法。

顏色常數在“Colors”靜態類別中作為唯讀屬性提供。

下列方法轉換成了名稱不同的屬性:

GDScript

C#

get_area()

Luminance

下列方法轉換成了名稱不同的屬性:

GDScript

C#

String[]

FromHtml(ReadOnlySpan<char>)

提供了以下方法,文件如下:

GDScript

C#

hex(int)

Color8

hex64(int)

Color8

陣列

與緊縮陣列等價的是 System.Array

另見 C# 中的緊縮資料

Godot.Collections.Array<T> 為類別安全版的 Godot.Collections.Array 封裝。可使用 Godot.Collections.Array<T>(Godot.Collections.Array) 建置函式來建立。

參見 c_sharp_signals

字典

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

Dictionary

變體

Godot.Variant 用來表示 Godot 的原生 Variant 型別。任何與 Variant 相容的型別都可以與其進行轉換。

參見 c_sharp_signals

與其他腳本語言溝通

本主題於 跨語言腳本撰寫 中詳細說明。

Onready 關鍵字

可以使用 C# 的 yield 關鍵字 來達到與在 GDScript 使用有單一參數的 yield 相同的功能。

C# 中的「await」關鍵字可以與任何可等待表達式一起使用。它通常與 TaskTask<TResult>ValueTaskValueTask<TResult> 型別的運算元一起使用。

回應事件將是包含以下欄位的字典:

  • t 是編譯時型別``dynamic``。

  • t 有一個名為 GetAwaiter 的可存取實例或擴充方法,沒有參數和型別參數,並且傳回型別 A 滿足以下所有條件:

    • A 實作介面``System.Runtime.CompilerServices.INotifyCompletion``。

    • “A” 有一個可存取、可讀的實例屬性“IsCompleted”,型別為“bool”。

    • “A” 有一個可存取的實例方法“GetResult”,沒有參數,也沒有型別參數。

對訊號的 yield 可以使用 async/await 與 Godot.Object.ToSignal 來達到同等效果。

範例:

await ToSignal(timer, "timeout");
GD.Print("After timeout");