Can i do extends get_parent()

Godot Version

Godot 4

Question

Is there any way i can do extends get_parent() instead of extends Node?

you can extend from a base type. Sprite2D inherits from Node->CanvasItem->Node2D. So you could extend from Node,CanvasItem or Node2D.

|Node
|-CanvasItem
|–Node2D
|—Sprite2D

#extends Node
#extends CanvasItem
extends Node2D
#extends Sprite2D

func  _ready():
	print(name)
	print(global_position)

the thing is i dont know what object i will be inheriting from. i have a node that holds a script an example is maybe a basic movement script. then i want to give that script to a player and an enemy. so i add the node as a child of the player and also a child of the enemy in the respective scenes. so now i need to extend from the node’s parent in order to access stuff like position (i know i could use get_node in the prosess functions but that would be sloppy)

playerNode
----nodeScript(extends get_parent() which is playerNode)

the only problem is idk how to extend only based on what is a parent.

get_parent() is a function that belongs to the Node class. functions cannot be used with extend.

you must know what class you are extending from.

in c# extends Sprite2D is written:

public class MyEnemy:Sprite2D {
   // code
}

above, my MyEnemy class inherits from Sprite2D.

so there’s no way to inherit based on parentage in gd script?

correct. you cannot do this in any mainstream language that i aware of. definitely not c#

I think you may be mixing Nodes (in the tree) with “classes” in code.

Classes can inherit from other classes, although only single-inheritance.

A ‘class’ (coming from Node) is a Node. Put one in the tree and it gets parents and siblings and children. I think of these as family above, alongside and below.

hth

ETA - You can put any node anywhere. It’s up to the node to handle its surroundings.

You can use Composition instead, which is having the parent reference in the child node, and call whatever method you want from the parent.
Something like:

@export var parent: Node2D

func child_method():
    if parent.has_method("parent_method"):
        parent.parent_method()

As @shrooms said Inheritance comes with limitation that the inherited class should be known ahead of time.
Hope that helps.

1 Like