How to check if node inherits something

This script only works if the node inherits a BUILT IN class, not if i make the class and make a node that inherits it

func get_child_of_type(node: Node, target_type_string: String):
	for child in node.get_children():
		# Check if the child has a script attached
		if child.get_script() != null:
			# Check if the script's global class name matches the target string
			if child.is_class(target_type_string) or child.get_script().get_global_name() == target_type_string:
				return child
	return null

Usually if you want to test if a node is a user defined class you can just do.

n1 = MyClass
n2 = MyExtendedClass # extends MyClass
n3 = MyExtendedExtendedClass # extends MyExtendedClass
print (n1 is MyClass) # prints true
print (n2 is MyClass) # prints true
print (n3 is MyClass) # prints true

If you want to map the inheritance use the Script functions. get_base_script() and get_global_name()

2 Likes

I could’t find a way too and wrote a static class:

class_name ClassManager extends RefCounted

## A list of class info that user defined
static var DIC_CLASS:Array[Dictionary]

static func _static_init() -> void:
	DIC_CLASS = ProjectSettings.get_global_class_list()

static func fetch(cls_name:String) -> Dictionary:
	for dic_info in DIC_CLASS:
		if dic_info['class'] == cls_name:
			return dic_info
	return {}

static func is_child(parent:String, child:String, recursive:bool = false) -> bool:
	var dic_info = fetch(child)
	if not dic_info:
		return false
	if dic_info['base'] == parent:
		return true
	else:
		if recursive:
			return is_child(parent, dic_info['base'], true)
		return false

use ClassManager.is_child everywhere when needed. And I really hope Godot can support this feature better and officially.

1 Like

Check out my code snippet here, fully type safe, not String based.

2 Likes

smack me on the ass and call me Patricia

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.