Hello everyone! In Godot 4 Beta, I had this piece of code:

func get_random_item_instance_by_type(type):
	var items_of_type = items.values().filter(
		func(v: Item):
			return v is type
	)
	var rand_idx = randi() % items_of_type.size()
	return create_instance(items_of_type[rand_idx])

And it was called like this:
get_random_item_instance_by_type(MeleeWeapon)
where MeleeWeapon is a class_name
But now that I've updated to 4.0.3, it breaks on "v is type" part, saying that "type" is now a known type. How can I achieve the same result of dynamically checking a type? I already tried with typeof and is_class() but none of them worked.

  • xyz replied to this.

    Hozerino The main question is: was it a bug then or is it a bug now 🙂
    You should probably report this as an issue and see what the devs say.

    You would use typeof. I just tried it with a class I made called Cat and a object of var name cat

    print(typeof(cat) == typeof(Cat)) # it's true
    • xyz replied to this.

      cybereality Unfortunately typeof() only distinguishes between different Variant types. It'll return the same typeid for all custom class objects.

      Strange. It seems like this is not possible. None of the functions can return a custom class_name. I also tried looking in the property list and meta, there is nothing there.

      • xyz replied to this.

        cybereality The is keyword is supposed to handle this. But as we can see from the OP, it refuses to do so if the class is not specified as a literal.

        Also, the second argument used in is needs to define a type, not a variable. So I'm not sure how this could work.

        • xyz replied to this.

          cybereality You can pass classes around similarly to how you'd do it in Python.
          Check this:

          var n = Node
          print(n)

          It'll say that n is a class.

          Yes, you can pass the class. But using is requires the second part to be a literal.

          • xyz replied to this.

            cybereality Yes, you can pass the class. But using is requires the second part to be a literal.

            That's what I said 🙂
            But apparently, according to OP, this was possible in beta, and now it isn't.

            Got it working by using is_instance_of.