Up to date
This page is up to date for Godot 4.2
.
If you still find outdated information, please open an issue.
C# language features¶
На цій сторінці ви знайдете огляд часто використовуваних функцій як C#, так і Godot, та способів їх спільного використання.
Перетворення типів і кастинг¶
C# - це статично типізована мова. Тому ви не можете зробити наступне:
var mySprite = GetNode("MySprite");
mySprite.SetFrame(0);
The method GetNode()
returns a Node
instance.
You must explicitly convert it to the desired derived type, Sprite2D
in this case.
Для цього у вас є різні варіанти в C#.
Приведення та перевірка типу
Throws InvalidCastException
if the returned node cannot be cast to Sprite2D.
You would use it instead of the as
operator if you are pretty sure it won't fail.
Sprite2D mySprite = (Sprite2D)GetNode("MySprite");
mySprite.SetFrame(0);
Використання оператора AS
The as
operator returns null
if the node cannot be cast to Sprite2D,
and for that reason, it cannot be used with value types.
Sprite2D mySprite = GetNode("MySprite") as Sprite2D;
// Only call SetFrame() if mySprite is not null
mySprite?.SetFrame(0);
Використання загальних методів
Також передбачені загальні методи, щоб зробити перетворення цього типу прозорим.
GetNode<T>()
переводить вузол перед поверненням. Він видасть, InvalidCastException
якщо вузол не може бути приведений до бажаного типу.
Sprite2D mySprite = GetNode<Sprite2D>("MySprite");
mySprite.SetFrame(0);
GetNodeOrNull<T>()
використовує оператор as
і поверне null
, якщо вузол неможливо перетворити на потрібний тип.
Sprite2D mySprite = GetNodeOrNull<Sprite2D>("MySprite");
// Only call SetFrame() if mySprite is not null
mySprite?.SetFrame(0);
Перевірка типу за допомогою оператора IS
To check if the node can be cast to Sprite2D, you can use the is
operator.
The is
operator returns false if the node cannot be cast to Sprite2D,
otherwise it returns true. Note that when the is
operator is used against null
the result is always going to be false
.
if (GetNode("MySprite") is Sprite2D)
{
// Yup, it's a Sprite2D!
}
if (null is Sprite2D)
{
// This block can never happen.
}
You can also declare a new variable to conditionally store the result of the cast
if the is
operator returns true
.
if (GetNode("MySprite") is Sprite2D mySprite)
{
// The mySprite variable only exists inside this block, and it's never null.
mySprite.SetFrame(0);
}
Більш просунуту перевірку типу ви можете подивитись у Відповідність шаблонів.
Preprocessor визначення¶
У Godot є набір визначень, які дозволяють змінювати ваш C# код залежно від середовища.
Примітка
Якщо ви створили свій проєкт до Godot 3.2, ви повинні змінити, або відновити ваш файл csproj, щоб використовувати цю функцію (порівняйте <DefineConstants>
з новим проєктом 3.2+).
Приклади¶
Наприклад, ви можете змінити код на основі платформи:
public override void _Ready()
{
#if GODOT_SERVER
// Don't try to load meshes or anything, this is a server!
LaunchServer();
#elif GODOT_32 || GODOT_MOBILE || GODOT_WEB
// Use simple objects when running on less powerful systems.
SpawnSimpleObjects();
#else
SpawnComplexObjects();
#endif
}
Або ви можете виявити, в якому движку знаходиться ваш код, корисний для створення між-движкових бібліотек:
public void MyPlatformPrinter()
{
#if GODOT
GD.Print("This is Godot.");
#elif UNITY_5_3_OR_NEWER
print("This is Unity.");
#else
throw new NotSupportedException("Only Godot and Unity are supported.");
#endif
}
Or you can write scripts that target multiple Godot versions and take advantage of features that are only available on some of those versions:
public void UseCoolFeature()
{
#if GODOT4_3_OR_GREATER || GODOT4_2_2_OR_GREATER
// Use CoolFeature, that was added to Godot in 4.3 and cherry-picked into 4.2.2, here.
#else
// Use a workaround for the absence of CoolFeature here.
#endif
}
Повний список визначень¶
GODOT
завжди визначається для проєктів Godot.TOOLS
is defined when building with the Debug configuration (editor and editor player).GODOT_REAL_T_IS_DOUBLE
is defined when theGodotFloat64
property is set totrue
.GODOT_64
, абоGODOT_32
, визначається залежно від того, чи архітектура 64-бітна, чи 32-бітна.One of
GODOT_LINUXBSD
,GODOT_WINDOWS
,GODOT_OSX
,GODOT_ANDROID
,GODOT_IOS
,GODOT_HTML5
, orGODOT_SERVER
depending on the OS. These names may change in the future. These are created from theget_name()
method of the OS singleton, but not every possible OS the method returns is an OS that Godot with .NET runs on.GODOTX
,GODOTX_Y
,GODOTX_Y_Z
,GODOTx_OR_GREATER
,GODOTX_y_OR_GREATER
, andGODOTX_Y_z_OR_GREATER
, whereX
,Y
, andZ
are replaced by the current major, minor and patch version of Godot.x
,y
, andz
are replaced by all values from 0 to the current version number for that component.Примітка
These defines were first added in Godot 4.0.4 and 4.1. Version defines for prior versions do not exist, regardless of the current Godot version.
For example: Godot 4.0.5 defines
GODOT4
,GODOT4_OR_GREATER
,GODOT4_0
,GODOT4_0_OR_GREATER
,GODOT4_0_5
,GODOT4_0_4_OR_GREATER
, andGODOT4_0_5_OR_GREATER
. Godot 4.3.2 definesGODOT4
,GODOT4_OR_GREATER
,GODOT4_3
,GODOT4_0_OR_GREATER
,GODOT4_1_OR_GREATER
,GODOT4_2_OR_GREATER
,GODOT4_3_OR_GREATER
,GODOT4_3_2
,GODOT4_3_0_OR_GREATER
,GODOT4_3_1_OR_GREATER
, andGODOT4_3_2_OR_GREATER
.
Під час експортування також можна визначити наступне залежно від особливостей експорту:
Залежно від типу платформи
GODOT_PC
,GODOT_MOBILE
, абоGODOT_WEB
.One of
GODOT_WINDOWS
,GODOT_LINUXBSD
,GODOT_MACOS
,GODOT_ANDROID
,GODOT_IOS
, orGODOT_WEB
depending on the platform.
Щоб побачити приклад проєкту, дивіться демонстраційну версію тестування ОС: https://github.com/godotengine/godot-demo-projects/tree/master/misc/os_test