Help with inheritance design

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

Hi,
I am new to Godot and I’m trying to understand how I can implement inheritance. I am writing my first game and in the game there will be 20-25 RigidBody2D objects which will have exactly the same behaviours: when clicked (input_event signal), they play a sound and then disappear (queue_free()). Only difference between them is that they have different sprites (different shapes, i.e. rectangle, circle, square etc.) and different CollisionPolygon2D’s. Can you please kindly suggest a way to achieve this? I started with a RigidBody2D, made it a class and inherited from that. But that way, signalling the input_event in the script gets messed up. The scenes inherited from that class gets created with the signal of the original class. Maybe this is a stupid question but as I said I am a newbie just trying to learn the engine.
Thank you in advance

:bust_in_silhouette: Reply From: ntfshard

Hello
I’m also beginner but may be my advice could help. I’m not quite understand your design flaw but if you have a mess with binding signals and functions you probably should try doing it not in editor. Try to use constructor (func _ready) of a base class and bind it in runtime. Signals — Godot Engine (3.2) documentation in English

In this case you have concrete self and function and signal name. Also you could just hook up one script to several nodes. May be also you can rid of inheritance.

Hi,
Actually my intention was not to connect signals in code, but that is also very helpful.
Thank you.

korayozbay | 2020-05-08 03:51

I’m working on such design now (may be you could take some ideas from it):

I have multiple Area2D(to have input_event) as a parent/root of item and couple child-plugins, like context menu or left_button_action. Each Area2D has specific for such type of item code in ‘agreed’-named functions like do_inspect, do_take, do_…
Each child-plugin can be added as a child(wow) to any Area2D. In child-plugin’s _ready function he binds to parent’s input_event handler.
For example, context menu has code like: if it’s right_mouse_button pressed, then show menu. Menu has several buttons. Each button has code(inside plugin):
if parent.has_method(“do_take”): parent.do_take(some args from event) else assert(false)
Also it’s possible to hide buttons, if you wish.

May be it’s reinventing something already made inside engine but I don’t find anything. This mechanism is more like poor man’s virtual functions/polymorphism

ntfshard | 2020-05-09 21:43

:bust_in_silhouette: Reply From: anothervenue

Not sure I understand the problem completely, but you can also extend the script, not just the scene.

So don’t define the signal in the base script, but in the extended ones for each type extended from that base type.