Best way of "emulating" multiple inheritance?

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

Hi there!

First of all, I’m aware that multiple inheritance is not allowed, and for good reasons too! But I’m trying to find the Godot way around it to avoid having duplicate code.

Here’s my situation:

  • I have a turret class that shoots targets entering its area
  • I also have a base enemy class, what it does is not relevant
  • I have a tank class which extends enemy
    The thing is, the tank has the same shooting mechanics as the turret, in fact they share some nodes and pieces of code. Problem is tank needs to extend enemy, so I can’t really reuse the turret code and I have to duplicate it and place it in the tank script.

Is there a way to avoid duplicating the shooting code? Ideally I would have the shooting mechanics written in a script and have both tank and turret use it.

:bust_in_silhouette: Reply From: omggomb

Is there a way to avoid duplicating the shooting code? Ideally I would have the shooting mechanics written in a script and have both tank and turret use it.

I would extract the shooting code into its own script and attach nodes using that script to both the turret and the tank. You just need to refactor your shooting code to work with the parent node instead of the one it is attached to. It’s basically using composition (more acurately aggregation) instead of inheritance. Godot allows for both, though it has more of an inheritance vibe to it.

This is a great answer IMO, thank you.
I have never thought about this, but it feels the right way to leverage component-based programming in Godot.

DodoIta | 2022-06-01 11:38