How to compare class_name with String?

This won’t work unfortunately with the custom classes :frowning:

bool is_class(class: String) const
Returns true if the object inherits from the given class. See also get_class().
Note: This method ignores class_name declarations in the object’s script.

Surprisingly, this isn’t that easy. What I came up with is the following:

func get_type_as_string(object: Object) -> String:
	if object == null:
		return ""
	
	var script: Script = object.get_script()
	if script == null:
		return object.get_class()
	
	var type_as_string: String = script.get_global_name()
	if type_as_string == "":
		type_as_string = script.get_instance_base_type()
	
	return type_as_string


func on_Target_hit(hit):
	if get_type_as_string(hit) == target:
		...

EDIT: updated the function to work with the built-in types as well
EDIT 2: update the function to work with objects without a script.

2 Likes