This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

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?"

Godot version 3.4.2
in Engine by (93 points)

2 Answers

+3 votes

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".

by (1,656 points)
+1 vote

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")
by (1,122 points)

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.

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.