Skip to main content

Dynamic Variable Creation in GDScript: Cloning Types at Runtime

One of the recent struggles I had with GDScript was trying to create a new variable at runtime with a dynamic type, based on the type of an existing variable.

This is the code I ended up with:

global_class_dict: Dictionary in ProjectSettings.get_global_class_list() # Get the list of classes in the project
if global_class_dict["class"] == (other_instance.get_script() as Script).get_global_name()
var instance: Resource = load((global_class_dict["path"] as String)) # Load the script of the wanted class
return instance.call("new", param_1, param_2, ...) # Instantiate the new class with whatever parameter is needed