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

by (1,558 points)
+1 vote

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")
by (1,083 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.