0 votes

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.

Godot version 4.0-alpha8
in Engine by (563 points)

1 Answer

+1 vote
Best answer

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.

by (1,385 points)
selected by

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.

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.