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.

일반적인 엔진 메소드 및 매크로

Godot의 C++ 코드베이스는 거의 모든 파일에서 사용되는 수십 개의 사용자 정의 방법과 매크로를 사용합니다. 이 페이지는 초보 기여자를 대상으로 하지만 사용자 정의 C++ 모듈을 작성하는 사람에게도 유용할 수 있습니다.

서식(Formatting)

vformat() 함수는 형식이 지정된 :ref:`class_String`를 반환합니다. C의 ``sprintf()``와 유사한 방식으로 동작합니다.

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").utf8().get_data();

대부분의 경우 문자열 연결 대신 ``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);

문자열 국제화

Godot에는 UI를 디자인하는 두 가지 방법이 있습니다. 먼저 당신은:

  • TTR(): **편집기("도구") 번역**은 편집기에서만 처리됩니다. 사용자가 프로젝트 중 하나에서 동일한 텍스트를 사용하는 경우 번역을 제공하면 번역되지 않습니다. 엔진에 기여할 때 일반적으로 현지화 가능한 문자열에 사용해야 하는 매크로입니다.

  • RTR(): **런타임 번역**은 지정된 문자열에 대한 번역을 제공하는 경우 프로젝트에서 자동으로 현지화됩니다. 이러한 종류의 번역은 편집기 전용 코드에서 사용하면 안 됩니다.

// 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

이는 다른 값(예: intfloat)과 비교할 수 있는 모든 유형에서 작동합니다.

마이크로벤치마킹

코드 조각을 벤치마킹하고 싶지만 프로파일러 사용 방법을 모르는 경우 다음 코드 조각을 사용하세요.

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/time.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() 함수의 반대 방식으로 작동합니다. 내부 조건이 ``false``가 아닌 ``true``로 평가되면 오류가 발생합니다.

참고

여기에는 사용자 정의 메시지가 있는 변형만 문서화되어 있습니다. 이는 항상 새로운 기여에 사용되어야 하기 때문입니다. 제공된 사용자 지정 메시지에 사람들이 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.");

더 보기

각 오류 매크로에 대한 자세한 정보는 Godot의 코드베이스에서 core/error/error_macros.h를 참조하세요.

일부 함수는 오류 코드를 반환합니다(반환 유형 ``Error``로 구체화됨). 이 값은 오류 매크로에서 직접 반환될 수 있습니다. `core/error/error_list.h <https://github.com/godotengine/godot/blob/master/core/error/error_list.h>`__에서 사용 가능한 오류 코드 목록을 참조하세요.