How to get if a global class inherits another global class with just the names

Godot Version

4.6 stable

Question

Is there a way to check if a script defined class inherits another script defined class by class name? Basically ClassDB.is_parent_class() equivalent for global GDScript class_name classes. Right now I do this by fetching the class dictionary using ProjectSettings.get_global_class_list(), making a new instance with var instance = load(cls["path"]).new() and then checking using the is keyword if instance is ParentClass. Is there a way to do this using just the StringName’s of the classes? Or just a cleaner way to write this:

# Returns an instance of a class named 'name' that inherits ParentClass or null on fail.
static func get_inherited_class_by_name(name: String) -> ParentClass:
	for cls in ProjectSettings.get_global_class_list():
		if cls["class"] == name:
			var cls_instance = load(cls["path"]).new() as Object
			if cls_instance is ParentClass:
				return cls_instance
			if cls_instance is RefCounted:
				cls_instance.unreference()
			else:
				cls_instance.free()
			break
	printerr("Global Class '%s' does not exist or it does not extend ParentClass." % name)
	return null

What’s the use case for this?

1 Like

Script.get_instance_base_type() may be what you are looking for.

This returns the engine builtin type. I need a way to get if two script class_name classes have a ancestor relationship.

I’m working on a tool and maybe plugin for encoding and decoding resources to and from json for a safe savefile system. The way I’m doing it now all save files must extend the SaveFile class. What I have works, I was just hoping there’d be a way to check if the file that is trying to be loaded extends SaveFile without having to make new instances only for one simple check.