Checking object custom class dynamically

Godot Version

4.5

Question

I’m trying to write a function that checks the custom class of the resource that is put into inventory slot. However, i want the custom class that the resource is checked against to be changeable at runtime - so instead of hardcoding if this_resource is this_type, i’ll like something where this_type is a variable that can be changed. Is this possible?

i know i can use get_script() or get_global_name() to achieve something of a similar effect, but as most of my items actually inherits from subclasses with a different script and a global name, these won’t always work.

thanks!!!

You can use is_instance_of() and provide this_type as a second argument.

if is_instance_of(this_resource, this_type):
	# do something

thanks! turns out i was overcompilcating it haha

1 Like

actually… what if i want to be able to change this_type from the inspector by selecting it from a enum? Using find_key() returns the right this_type, but is_instance_of throws an error…

Yeah, enums kinda break it, as they store keys as String type. You’d need to convert it back from String to a type. Do you need this though, or can you live without it?

huh I didn’t know that… if it’s not too much of a bother, do you mind telling me how would i go about doing that?

In this case, I think it’d be easier to do it the other way around - convert the type to String and then compare.
See my reply in this thread, where I provided a script that should reliably do that for all classes - built-in and custom.

1 Like

Thank you so much!! I was about to brute force it, but your dictionary implementation is much nicer :grin: so I’m going to go with that.

1 Like