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.
Checking the stable version of the documentation...
Загальні методи двигуна та макроси
Кодова база Godot C++ використовує десятки спеціальних методів і макросів, які використовуються майже в кожному файлі. Ця сторінка орієнтована на початківців учасників, але вона також може бути корисною для тих, хто пише спеціальні модулі C++.
Роздрукувати текст
// Prints a message to standard output.
print_line("Message");
// Non-String arguments are automatically converted to String for printing.
// If passing several arguments, they will be concatenated together with a
// space between each argument.
print_line("There are", 123, "nodes");
// Prints a message to standard output, but only when the engine
// is started with the `--verbose` command line argument.
print_verbose("Message");
// Prints a rich-formatted message using BBCode to standard output.
// This supports a subset of BBCode tags supported by RichTextLabel
// and will also appear formatted in the editor Output panel.
// On Windows, this requires Windows 10 or later to work in the terminal.
print_line_rich("[b]Bold[/b], [color=red]Red text[/color]")
// Prints a formatted error or warning message with a trace.
ERR_PRINT("Message");
WARN_PRINT("Message");
// Prints an error or warning message only once per session.
// This can be used to avoid spamming the console output.
ERR_PRINT_ONCE("Message");
WARN_PRINT_ONCE("Message");
Якщо вам потрібно додати заповнювачі у свої повідомлення, використовуйте рядки форматування, як описано нижче.
Відформатувати рядок
Функція vformat()
повертає форматований String. Він поводиться подібно до sprintf()
C:
vformat("My name is %s.", "Godette");
vformat("%d bugs on the wall!", 1234);
vformat("Pi is approximately %f.", 3.1416);
// Converts the resulting String into a `const char *`.
// You may need to do this if passing the result as an argument
// to a method that expects a `const char *` instead of a String.
vformat("My name is %s.", "Godette").c_str();
У більшості випадків спробуйте використовувати vformat()
замість конкатенації рядків, оскільки це робить код більш читабельним.
Перетворення цілого числа або числа з плаваючою речовиною на рядок
Це не потрібно під час друку чисел за допомогою print_line()
, але вам все одно може знадобитися виконати перетворення вручну для деяких інших випадків використання.
// Stores the string "42" using integer-to-string conversion.
String int_to_string = itos(42);
// Stores the string "123.45" using real-to-string conversion.
String real_to_string = rtos(123.45);
Інтернаціоналізація рядка
Існує два типи інтернаціоналізації в кодовій базі Годо:
TTR()
: Переклади редактора ("інструментів") оброблятимуться лише в редакторі. Якщо користувач використовує той самий текст в одному зі своїх проектів, він не буде перекладено, якщо він надасть для нього переклад. Під час додавання до механізму, це, як правило, макрос, який ви повинні використовувати для локалізованих рядків.RTR()
: Runtime translations will be automatically localized in projects if they provide a translation for the given string. This kind of translation shouldn't be used in editor-only code.
// Returns the translated string that matches the user's locale settings.
// Translations are located in `editor/translations`.
// The localization template is generated automatically; don't modify it.
TTR("Exit the editor?");
Щоб вставити заповнювачі в локалізовані рядки, оберніть макрос локалізації у виклик vformat()
таким чином:
String file_path = "example.txt";
vformat(TTR("Couldn't open \"%s\" for reading."), file_path);
Примітка
Використовуючи vformat()
і макрос перекладу разом, завжди загортайте макрос перекладу в vformat()
, а не навпаки. Інакше рядок ніколи не збігатиметься з перекладом, оскільки в ньому буде вже замінено покажчик місця заповнення під час передачі на TranslationServer.
Закріпити значення
Godot надає макроси для обмеження значення з нижньою межею (MAX
), верхньою межею (MIN
) або обома (CLAMP
):
int a = 3;
int b = 5;
MAX(b, 6); // 6
MIN(2, a); // 2
CLAMP(a, 10, 30); // 10
Це працює з будь-яким типом, який можна порівняти з іншими значеннями (наприклад, int
і float
).
Мікробенчмаркінг
Якщо ви хочете порівняти фрагмент коду, але не знаєте, як користуватися профайлером, скористайтеся цим фрагментом:
uint64_t begin = Time::get_singleton()->get_ticks_usec();
// Your code here...
uint64_t end = Time::get_singleton()->get_ticks_usec();
print_line(vformat("Snippet took %d microseconds", end - begin));
Це надрукує час, витрачений між оголошенням begin
і end
декларацією.
Примітка
Можливо, вам доведеться #include "core/os/os.h"
, якщо його ще немає.
Можливо, вам такий #include "core/os/os.h"
, якщо його ще немає.
Отримати налаштування проекту/редактора
Для цього доступні чотири макроси:
// Returns the specified project setting's value,
// defaulting to `false` if it doesn't exist.
GLOBAL_DEF("section/subsection/value", false);
// Returns the specified editor setting's value,
// defaulting to "Untitled" if it doesn't exist.
EDITOR_DEF("section/subsection/value", "Untitled");
Якщо значення за умовчанням було вказано деінде, не вказуйте його знову, щоб уникнути повторення:
// Returns the value of the project setting.
GLOBAL_GET("section/subsection/value");
// Returns the value of the editor setting.
EDITOR_GET("section/subsection/value");
Рекомендовано використовувати GLOBAL_DEF
/EDITOR_DEF
лише один раз для налаштування та використовувати GLOBAL_GET
/EDITOR_GET
у всіх інших місцях, де на нього є посилання.
Макроси помилок
Godot містить багато макросів помилок, щоб зробити повідомлення про помилки зручнішим.
Попередження
Умови в макросах помилок працюють протилежно до вбудованої функції GDScript assert()
. Стається помилка, якщо умова всередині має значення true
, а не false
.
Примітка
Тут задокументовано лише варіанти з користувацькими повідомленнями, оскільки їх слід завжди використовувати в нових дописах. Переконайтеся, що надане спеціальне повідомлення містить достатньо інформації, щоб люди могли діагностувати проблему, навіть якщо вони не знають C++. Якщо метод отримав недійсні аргументи, ви можете надрукувати недійсне значення, щоб полегшити налагодження.
Для внутрішньої перевірки помилок, коли відображення зрозумілого для людини повідомлення не є обов’язковим, видаліть _MSG
у кінці назви макросу та не вказуйте аргумент повідомлення.
Крім того, завжди намагайтеся повертати придатні для обробки дані, щоб система могла нормально працювати.
// Conditionally prints an error message and returns from the function.
// Use this in methods which don't return a value.
ERR_FAIL_COND_MSG(!mesh.is_valid(), vformat("Couldn't load mesh at: %s", path));
// Conditionally prints an error message and returns `0` from the function.
// Use this in methods which must return a value.
ERR_FAIL_COND_V_MSG(rect.x < 0 || rect.y < 0, 0,
"Couldn't calculate the rectangle's area.");
// Prints an error message if `index` is < 0 or >= `SomeEnum::QUALITY_MAX`,
// then returns from the function.
ERR_FAIL_INDEX_MSG(index, SomeEnum::QUALITY_MAX,
vformat("Invalid quality: %d. See SomeEnum for allowed values.", index));
// Prints an error message if `index` is < 0 >= `some_array.size()`,
// then returns `-1` from the function.
ERR_FAIL_INDEX_V_MSG(index, some_array.size(), -1,
vformat("Item %d is out of bounds.", index));
// Unconditionally prints an error message and returns from the function.
// Only use this if you need to perform complex error checking.
if (!complex_error_checking_routine()) {
ERR_FAIL_MSG("Couldn't reload the filesystem cache.");
}
// Unconditionally prints an error message and returns `false` from the function.
// Only use this if you need to perform complex error checking.
if (!complex_error_checking_routine()) {
ERR_FAIL_V_MSG(false, "Couldn't parse the input arguments.");
}
// Crashes the engine. This should generally never be used
// except for testing crash handling code. Godot's philosophy
// is to never crash, both in the editor and in exported projects.
CRASH_NOW_MSG("Can't predict the future! Aborting.");
Дивись також
Перегляньте core/error/error_macros.h в кодовій базі Godot, щоб отримати додаткові відомості про кожен макрос помилки.
Деякі функції повертають код помилки (матеріалізований типом повернення Error
). Це значення можна повернути безпосередньо з макросу помилки. Перегляньте список доступних кодів помилок у core/error/error_list.h.