How to add more than one script to an object without extending?

Godot Version

4.2.1

Question

I have been trying to reuse scripts in godot but it is very hard because an object can only have one. is there a way to have more than on script in godot without extending it?

One object can only have one script attached.

A few alternatives are:

  • Composition through nodes: Add child nodes that define some additional logic or data. An example for this is physics bodies, which use children to define their shape. This way a body can have multiple shapes. Or in the context of scripts, you can add empty nodes as children with your additional scripts. They can act upon the parent via get_parent() or, if you want something a bit more tree structure independent, use owner to get the root node of their respective scene file.
  • Composition through code: Basically you preload() your additional scripts and instantiate them via script. How you use them after that and how they communicate with each other is completely up to you.
  • Managers: sometimes instead of adding more components, it also makes sense to abstract things away into a manager autoload. For example instead of adding a component that can shoot bullets on each enemy (assuming a bullet hell style game), you may want a global BulletManager autoload that has a functions to spawn the different bullet types and can be used by all enemies.

Each node in a scene can have a separate script attached to it, so you can have multiple scripts in a single file. However, the ability is not as useful as it might seem, and I have found through personal experience that the need for that ability frequently indicates a systemic design flaw.