@jackhen said:
Thank you so much for the response, this is very helpful. I would like to have a method such as "attack()" that is different for all units, but is still called at the same time for all units. could I define attack to use in the parent class and then define its content in the child classes? Also I would like to define attributes of each unit to be used in other places, even when there is no instance of that unit (example the unit is in the store as a control node). should I be storing the units attributes in a packed scene and instantiating the unit to access its attributes, or is there a better way to store that info?
Yes! If you define a method in a parent class, you can define the method again in a child class, and the child method will override the parent method when you call it. The only exceptions are certain methods defined by Godot such as _process()
and _ready()
. (The code from both the parent and child method will always execute)
If you wanted to call the same method on all your units, you could put the units in a group, then use get_nodes_in_group()
to get all your units, and call your method on those. For example:
func make_units_attack():
var units = get_tree().get_nodes_in_group("Units")
for unit in units:
unit.attack()
As for accessing data on scenes that may not exist in the current scene, there are a couple of approaches. Your store could hold references to the unit scenes in export variables. You would still need to instantiate the scene using the instance()
method in order to access its attributes, but you do not actually have to add the instance to the scene. Example:
export var unit:PackedScene
func print_unit_cost():
print(unit.instance().cost)
Depending on how big your unit scene is though, this might use up a fair amount of memory. If that is a concern, just make sure you aren't keeping any references to units that you no longer need to access attribute info from.