Is there any way to transform a String to a class_name type I can use for an “is” check? I’m using a string here, because there doesn’t seem to be a way to use class_name types for an @export dropdown list?
Bird.gd
class_name Bird
func hit():
SignalManager.emit_signal("Target_hit", self)
Task.gd
@export_enum("Bird", "Crow") var target: String = "Bird"
func _enter_tree() -> void:
SignalManager.Target_hit.connect(on_Target_hit)
func on_Target_hit(hit):
if hit is target: <-- does not work, because "is" needs a type and not a String
.....
This won’t work unfortunately with the custom classes
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.
Unfortunately, I just discovered that it doesn’t work with inherited class names. Crow-check works, Bird-check does not.
class_name Crow extends Bird
Since that solution was already very complicated, it’s probably not possible to check for inherited class names, right? I’ll do the check for inherited classes manually then.
It’s not possible with this solution I did, because it checks the actual class, ignoring any inheritance.
What you can do is what @OriginalBadBoy suggested, but you don’t need any global enum, you can do it locally too. Simply something like that should work:
@export_enum("Bird", "Crow") var target: String = "Bird"
var class_map: Dictionary[String, Variant] = {
"Bird": Bird,
"Crow": Crow
}
func on_Target_hit(hit):
if is_instance_of(hit, class_map[target]):
...