How do you check if an object is the descendent of a custom class?

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

I have a script called “MapObject” that extends “Node2D.” Then, I have a script called “Enemy” that extends “MapObject.” How would I check if an enemy object is a “MapObject?”

:bust_in_silhouette: Reply From: AlexTheRegent

if your MapObject (res://map_object.gd) extends Node2D:

extends Node2D

and Enemy (res://enemy.gd) extends MapObject:

extends "res://map_object.gd"

then you can check instance using if instance == preload("res://map_object.gd"):

var enemy = load("res://enemy.gd").new()
if enemy is preload("res://map_object.gd"):
	print("child")
else:
	print("not a child")

and it will output “child”.

:bust_in_silhouette: Reply From: Ninfur

If you name your classes, all you need to do is use the is-syntax.

MapObject.gd:

extends Node2D
class_name MapObject

Some other script:

if enemy is MapObject:
    print("Is descendent")

Note that named classes can’t have cyclic references and have various issues. preload, on other hand, will always work without quirks.
This is true for Godot 3.x, in Godot 4.x all these issues should be resolved. So, in Godot 3.x it is safer to go without named classes.

AlexTheRegent | 2022-06-30 22:54

Cyclic references are still a problem in Godot4.0.beta3

sirdorius | 2022-11-07 23:00