how do you get custom classes with a match statement?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By JoltJab

So I’m settin up a match statement to test what class of node I got, right? I’m using .get_class() to figure out what class it is, but then I find out it doesn’t return custom classes! Does anyone know how I could check what class (including custom classes) my node is?

example code:

@export var physics_parent: Node;

func check_physics_parent() -> void:
	match physics_parent.get_class():
			print("I'm characterBody2D");

			print("I'm RigidBody2D");

			print("I'm FunkyPhysicsClass2D");

			print("I'm most likely 'null'");

In the example above, “FunkyPhysicsClass2D” wouldn’t be called because “physics_parent.get_class()” wouldn’t get the custom class. Is there a way to fix this so the match statement works?

:bust_in_silhouette: Reply From: a_world_of_madness

You can use the is keyword to check if an object is a class or a sub-class of a certain type, here’s an example:

class MainClass:
class SubClass extends MainClass:

var main =
var sub =
print(main is MainClass) # true
print(sub is SubClass) # true,
print(main is SubClass) # false, 'main' does not extend 'SubClass'
print(sub is MainClass) # true, 'sub' is a sub-class of 'MainClass'

Here’s how it could be used to replace your match statement:

func check_physics_parent() -> void:
	if physics_parent is CharacterBody2D:
		print("I'm characterBody2D");
	elif physics_parent is RigidBody2D:
		print("I'm RigidBody2D");
	elif physics_parent is FunkyPhysicsClass2D:
		print("I'm FunkyPhysicsClass2D");
		print("I'm most likely 'null'");

oh, that’s perfect! Thank you for your help a_world_of_madness!

JoltJab | 2023-06-13 15:17