Skip to content

Commit 4d43fe1

Browse files
committed
Merge pull request #91472 from vnen/gdscript-default-static-variables-non-tool
GDScript: Initialize static variables with defaults in-editor
2 parents d798094 + 2223638 commit 4d43fe1

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

modules/gdscript/gdscript.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -678,6 +678,27 @@ Error GDScript::_static_init() {
678678

679679
#ifdef TOOLS_ENABLED
680680

681+
void GDScript::_static_default_init() {
682+
for (const KeyValue<StringName, MemberInfo> &E : static_variables_indices) {
683+
const GDScriptDataType &type = E.value.data_type;
684+
// Only initialize builtin types, which are not expected to be `null`.
685+
if (!type.has_type || type.kind != GDScriptDataType::BUILTIN) {
686+
continue;
687+
}
688+
if (type.builtin_type == Variant::ARRAY && type.has_container_element_type(0)) {
689+
Array default_value;
690+
const GDScriptDataType &element_type = type.get_container_element_type(0);
691+
default_value.set_typed(element_type.builtin_type, element_type.native_type, element_type.script_type);
692+
static_variables.write[E.value.index] = default_value;
693+
} else {
694+
Variant default_value;
695+
Callable::CallError err;
696+
Variant::construct(type.builtin_type, default_value, nullptr, 0, err);
697+
static_variables.write[E.value.index] = default_value;
698+
}
699+
}
700+
}
701+
681702
void GDScript::_save_old_static_data() {
682703
old_static_variables_indices = static_variables_indices;
683704
old_static_variables = static_variables;
@@ -841,6 +862,9 @@ Error GDScript::reload(bool p_keep_state) {
841862
#ifdef TOOLS_ENABLED
842863
if (can_run && p_keep_state) {
843864
_restore_old_static_data();
865+
} else if (!can_run) {
866+
// Initialize static variables with sane default values even if the constructor isn't called.
867+
_static_default_init();
844868
}
845869
#endif
846870

modules/gdscript/gdscript.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,9 @@ class GDScript : public Script {
169169
GDScriptFunction *static_initializer = nullptr;
170170

171171
Error _static_init();
172+
#ifdef TOOLS_ENABLED
173+
void _static_default_init(); // Initialize static variables with default values based on their types.
174+
#endif
172175

173176
int subclass_count = 0;
174177
RBSet<Object *> instances;

0 commit comments

Comments
 (0)