Is there a way to instance a class based on a string or enum in GDScript?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Ramshell

I’d like to do something like

config.gd

extend Resource
class_name Config
enum Configuration { Option1, Option2, Option3 }
export(Configuration) var how_to_do_something = Option1

builder.gd

build(config : Config) -> OptionStrategy:
  # id like to do something like this to instance
  # the strategy classes Option1, Option2, Opntion3, and so on
  # get_class(config.how_to_do_something.string).new()

It might sound senseless. But I know that I will add more Options in the future, and I don’t want to maintain a match case in the builder for each Option I implement.

:bust_in_silhouette: Reply From: Zylann

I’m not aware of a way to instance by name from a string, but I know it’s possible to do it if you have the path of the script resource (i.e res://scripts/my_script.gd):

var instance = load(path_to_script).new()

Which btw is how scripts are deserialized in the first place :stuck_out_tongue: That’s what I did to implement savegames in my last game jam (along with a few selected properties).

I’ve been searching in the web about this. And sadly, it seems that it is not possible to convert enums to strings automatically. But yeah, I guess that doing load("%s.gd" % option_string_representation) would do the trick if I happen to have the string.

Ramshell | 2019-10-23 13:21

1 Like
:bust_in_silhouette: Reply From: MintSoda

For engine classes, use ClassDB.instance("ClassName")

For custom classes, it’s only possible to instance from script path. Also, script paths can be found at ProjectSettings.get_setting("_global_script_classes"). So it’s possible to get the script of a class by its class_name, even if you move the scripts around.

Or use a class from godot-next, ClassType, which implements everything about class for you. (Somehow it was slow last year I used it, I only use it for creating plugins though. )

To be honest, I don’t know why custom classes aren’t included in ClassDB. This is very inconvenient.

1 Like
:bust_in_silhouette: Reply From: exuin

For Godot 4, you can use the ClassDB method for built-in classes like MintSoda said. For custom classes, call ProjectSettings — Godot Engine (stable) documentation in English and iterate through the array to find the class you’re looking for. Then load it.

As of Godot 4.2 the method name has changed,

use ClassDB.instantiate("ClassName") as per the documentation

This is particularly helpful when using @tool mode where you need to use the class EditorPlugin.new() but if you run this in-game it’ll give the error

Parser Error: Native class “EditorPlugin” cannot be constructed as it is abstract.

image

Just replace it with

func _ready():
	if(Engine.is_editor_hint()):
		var _editor_plugin=ClassDB.instantiate("EditorPlugin")
2 Likes