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...
Metodi e macro comuni del motore
Il codice base C++ di Godot utilizza dozzine di metodi e macro personalizzati utilizzati in quasi tutti i file. Questa pagina è rivolta ai contributori principianti, ma può essere utile anche per chi scrive moduli C++ personalizzati.
Stampare testo
// 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");
Se devi aggiungere segnaposto nei tuoi messaggi, utilizza le stringhe di formato come descritto di seguito.
Formattare una stringa
La funzione vformat() restituisce una String formattata. Si comporta in modo simile a sprintf() di 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").utf8().get_data();
Nella maggior parte dei casi, prova a utilizzare vformat() invece di concatenare le stringhe poiché rende il codice più leggibile.
Convertire un intero o float in una stringa
Ciò non è necessario quando si stampano numeri tramite print_line(), ma potrebbe essere comunque necessario effettuare una conversione manuale in alcuni altri casi.
// 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);
Internazionalizzare una stringa
Ci sono due tipi di internazionalizzazione nei sorgenti di Godot:
TTR(): le traduzioni dell'editor ("tools") saranno elaborate solo nell'editor. Se un utente utilizza lo stesso testo in uno dei suoi progetti, questo non sarà tradotto se ne fornisce una traduzione. Quando contribuisci al motore, questa è generalmente la macro da utilizzare per le stringhe localizzabili.RTR(): Le traduzioni durante l'esecuzione saranno localizzate automaticamente nei progetti se forniscono una traduzione per la stringa specificata. Questo tipo di traduzione non si dovrebbe utilizzare nel codice esclusivo all'editor.
// 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?");
Per inserire segnaposto in stringhe localizzabili, racchiudere la macro di localizzazione in una chiamata vformat() come segue:
String file_path = "example.txt";
vformat(TTR("Couldn't open \"%s\" for reading."), file_path);
Nota
Quando si usano vformat() e una macro di traduzione insieme, è sempre necessario racchiudere la macro di traduzione in vformat(), non viceversa. Altrimenti, la stringa non corrisponderà mai alla traduzione, poiché il segnaposto sarà già stato sostituito quando verrà passata a TranslationServer.
Limitare un valore
Godot fornisce macro per limitare un valore con un limite inferiore (MAX), un limite superiore (MIN) o entrambi (CLAMP):
int a = 3;
int b = 5;
MAX(b, 6); // 6
MIN(2, a); // 2
CLAMP(a, 10, 30); // 10
Funziona con qualsiasi tipo che si può confrontare con altri valori (come int e float).
Microbenchmarking
If you want to benchmark a piece of code but don't know how to use a profiler, use this snippet:
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));
Questo stamperà il tempo trascorso tra la dichiarazione begin e la dichiarazione end.
Nota
Potrebbe essere necessario #include "core/os/time.h" se non è già presente.
Quando si apre una richiesta di pull, assicurarsi di rimuovere questo frammento e anche l'inclusione, se non c'era in precedenza.
Ottenere le impostazioni del progetto/editor
Ci sono quattro macro disponibili per questo:
// 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");
Se un valore predefinito è stato specificato altrove, non specificarlo di nuovo per evitare ripetizioni:
// Returns the value of the project setting.
GLOBAL_GET("section/subsection/value");
// Returns the value of the editor setting.
EDITOR_GET("section/subsection/value");
Si raccomanda di utilizzare GLOBAL_DEF/EDITOR_DEF solo una volta per impostazione e di utilizzare GLOBAL_GET/EDITOR_GET in tutti gli altri punti in cui viene fatta riferimento.
Macro di errore
Godot dispone di numerose macro di errore per rendere più conveniente la segnalazione degli errori.
Avvertimento
Le condizioni nelle macro di errore funzionano in modo opposto alla funzione assert() integrata in GDScript. Si verifica un errore se la condizione al suo interno restituisce true, non false.
Nota
Qui sono documentate solo le varianti con messaggi personalizzati, poiché si dovrebbero sempre utilizzare nelle nuove contribuzioni. Assicurarsi che il messaggio personalizzato fornito includa informazioni sufficienti per diagnosticare il problema, anche a chi non conosce il C++. Nel caso in cui a un metodo siano stati passati argomenti non validi, è possibile stampare il valore non valido in questione per facilitare il debug.
Per la verifica interna degli errori, quando non è necessario visualizzare un messaggio leggibile in chiaro, rimuovere _MSG alla fine del nome della macro e non fornire un argomento per il messaggio.
Inoltre, tenta sempre di restituire dati elaborabili affinché il motore possa continuare a funzionare bene.
// 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.");
Vedi anche
Vedere <https://github.com/godotengine/godot/blob/master/core/error/error_macros.h> nel codice di Godot per più informazioni riguardo ogni macro di errore.
Alcune funzioni restituiscono un codice di errore (materializzato da un tipo restituito di Error). Questo valore si può restituire direttamente da una macro di errore. Consultare l'elenco dei codici di errore disponibili in core/error/error_list.h.