I am making a game where the player buys different units from a store to assemble an lineup of units that fight enemies automatically. I would like to define a parent Unit that has all code common across all units. I would like to define properties and methods that only apply to an individual unit in each individual unit class.
1. can I instantiate a new specific unit without having a scene for each individual unit? I only have created a scene in the editor for the parent unit and only have .gd files for the children 2. what is the best way to store information about each unit where it can be accessed without adding the unit to the scene tree? like in the store I need access to the properties of specific units to display them, so I just made a 2D array of all my units properties as a singleton by instantiating and adding each unit as a child, storing its properties in the array, and then changing the scene, and get them using [unitId][propertyId] to display in the store. I feel like there has to be a better way to do that. 3. can I define a method in a parent class so that I can call it in the parent class, but define the method differently in each child class?

  1. Yes, Godot allows you to swap out the script on a node at runtime, so you could theoretically just use the same scene for all units and change the script via the set_script() method. As long as the nodes in the parent unit scene are the same as what you need for the child unit, there shouldn't be any errors. I would not recommend this, however, as I've found that it's usually more convenient to just have a separate scene saved so that you do not have to set up your scenes with code.

  2. There are several ways to do this, and the best answer is going to change depending on your desired project architecture and performance needs. I think your approach of storing your units in a singleton is a good idea. You do not actually need to add the instances to the scene, however. If you're storing references to scenes and you need to get a property from one of those scenes, you can do that with something like scene.instance().property.

  3. Yes, this is exactly how inheritance works in most object oriented languages, including GDScript. If a child class contains a method with the same name as a method in the parent class, the parent method is overridden with the child method.

2 years later