See all glossary terms

Custom Constructors

In Godot, you call .new() on a class to create a new instance. This invokes the _init() method, which is the constructor of the class.
Often, you might have interest in passing different arguments to the constructor. A good way of handling this is to make your own. For example, suppose you have an Item class like so:
class_name Item extends Area3D

var name := ""
var weight := 1
var cost := 10

func _init(p_name: String, p_weight: float, p_cost: int) -> void:
  name = p_name
  cost = p_cost
  weight = p_weight
If most items in your game have a weight of 1 and a cost of 10, you can create a convenience method to create items with default values:
class_name Item

# ...

static func create_default(p_name: String) -> Item:
  return Item.new(p_name, 1, 10)
Or maybe, if you wanted all properties to be optional, you could use a dictionary to set properties:
class_name Item

# ...

static func from_dictionary(props: Dictionary) -> Item:
  var item = Item.new()
  for key in props.keys():
    if key in item:
      item[key] = props[key]
  return item
Now you have three ways to create an item:
func _ready() -> void:
  var sword = Item.new("Sword", 2, 20)
  var default_sword = Item.create_default("Sword")
  var sword_from_dict = Item.from_dictionary({
    "name": "Sword",
    "weight": 2,
    "cost": 20
  })
You're not limited to new()! This frees you from having to remember the order of arguments when creating instances, and also allows you to keep _init() clean and simple.

See Also

Related terms in the Glossary