See all glossary terms

Init Function

In Godot, objects are created in a few different ways:
  1. Scene instantiation (e.g, var scene := SceneFile.instantiate()) creates nodes in memory, and their children, as well as any associated resources.
  2. Resource loading (e.g, var resource := load("resourse.tres")) creates a resource in memory, and all sub-resources.
  3. Calling .new() in your own code, such as var timer := Timer.new().
Every time an object is created through any method, the _init() function is called. In most languages, this is called the constructor function. _init() is used to set up an initial state, connecting signals, and other setup tasks.
But then what is _ready()?
When using nodes, you might be more familiar with the _ready() function. _ready() is called after _init(), and is used to set up the node's state after it's been added to the scene tree, and all its children have been added too.
When using nodes, you are forced to wait for them to be _ready() before you can interact with them. When creating objects in code, you can interact with them immediately after calling .new().
See the node lifecycle article for more information about the order in which functions are called.
_init() can be used to set up an initial state:
class_name StopwatchRecord

var date := ""

func _init() -> void:
  date = Time.get_datetime_string_from_system()
Calling var record := StopwatchRecord.new() would automatically call _init() and run the enclosed code.
It's possible to have parameters in _init():
class_name Person

var name := ""
var age := 0

func _init(initial_name: String, initial_age: int) -> void:
  name = initial_name
  age = initial_age
You would then provide those values with var person := Person.new("Gandalf", 24000).
Be careful with init parameters!
When Godot instantiates a scene, or loads a resource, it will not call new() with parameters, and so, any object that has parameters in _init() will fail to load.
Only use _init() in parameters if you're sure the object will only be created in code, through .new().
It's safer generally to either provide default arguments, or have a create() function.
Here's how you would do default arguments.
class_name Person

var name := ""
var age := 0

func _init(initial_name := "nobody", initial_age := 0) -> void:
  name = initial_name
  age = initial_age
In which case an empty .new() wouldn't trigger an error; And here's a create() function:
class_name Person

var name := ""
var age := 0

static func create(initial_name: String, initial_age: int) -> Person:
  var person := Person.new()
  person.name = initial_name
  person.age = initial_age
  return person
Now, calling Person.new() still works, but you can get the new() functionality by using Person.create().

See Also

Related terms in the Glossary