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:// extends Node2D:

extends Node2D

and Enemy (res:// extends MapObject:

extends "res://"

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

var enemy = load("res://").new()
if enemy is preload("res://"):
	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.

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