+1 vote

I'd like to do something like


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


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.

in Engine by (51 points)

3 Answers

+2 votes
Best answer

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.

by (330 points)
selected by
+1 vote

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 :p That's what I did to implement savegames in my last game jam (along with a few selected properties).

by (29,120 points)

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.

0 votes

For Godot 4, you can use the ClassDB method for built-in classes like MintSoda said. For custom classes, call https://docs.godotengine.org/en/stable/classes/class_projectsettings.html#class-projectsettings-method-get-global-class-list and iterate through the array to find the class you're looking for. Then load it.

by (8,550 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.