Multiple/varying constructors?

Godot Version

v4.5.stable.steam [876b29033]

Question

Is there any way to have multiple constructors with different parameters for a custom class? It’s easy enough to set up one/use the _init function, but with a custom class with a lot of variables that differ based on context of the call, I was hoping for a way to differentiate.

For elaboration:

  • Class has 10+ variables in total
  • Depending on where/why an instance of the class is created, not all of these are relevant and could therefore be loaded to a default, however in other cases most to all of these variables need to be loaded to a specific case-by-case value (ie: a passed parameter).
  • This class is not a Node/scene item, it’s an information-based class mainly pertaining to stats/information on things found within the project.

Is there a way to do this, or would I need something like a second class with various functions that create and return instances of the target class?

There is no function overloading in GDScript, constructors included. You can pass in an initializer object instead of multiple arguments. Or make an object factory.

Assuming your class is a node of some sort, you can (more or less) do this by making a companion global class that has a global create/init function and default arguments:

# Global/CritterFactory.gd

func make_duck(fly_speed: float) -> Critter:
    var critter = preload("res://critter.tscn").instantiate()
    critter.become_duck(fly_speed)
    return critter

func make_weasel(cunning: float, slipperiness: float) -> Critter:
    var critter = preload("res://critter.tscn").instantiate()
    critter.become_weasel(cunning, slipperiness)
    return critter