In Godot, nodes automatically run a number of virtual functions as they get created, added to the tree, and so on.Here are all of them, in order.
_init()
The first function to be called is _init(). Godot calls this function at creation, whether you created the node (by writing var node := Node.new()) or whether the node comes from an instantiated scene.You can add parameters to _init(); those become mandatory to pass when using .new(). For example:
class_nameHealthComponentextends Node
var health :=0func_init(initial_health:int)->void: health = initial_health
You would call that with var component := HealthComponent.new(10). However, be careful! If your _init() function takes parameters, the Godot engine won't be able to automatically instantiate it.For that reason, you probably should keep _init() without parameters.
_enter_tree()
Godot calls this function when the node gets added to the tree; i.e, immediately after using add_child(node).If a node has children, then all the children's _enter_tree() will be called recursively, until the last grand children. Whena node that enters the tree, its parent emits a child_entered_tree signal.
_ready()
Probably the lifecycle method you are most familiar with. This function is called in the grand-children first, then walks up the tree until the root. That means that when _ready() is called, all children are also ready._ready() functions opposite to _enter_tree(): _enter_tree starts at the root and goes down the tree, while _ready starts at the endmost nodes and climbs back up the tree until reaching the root.When a node finishes running its _ready() function, it dispatches the ready signal.
_process() and _physics_process()
These two functions run at different moments, depending on the framerate. By default, he _process() function will run uncapped, while the _physics_process() will run at 60fps.Both those functions can be turned off, with set_process(false) and set_physics_process(false) respectively.
_exit_tree()
Before a node gets removed from the tree, it runs the _exit_tree() function. This happens either when you call remove_child() from a parent, or when you free() or queue_free() a node. Similarly to _ready(), children's _exit_tree() are called first.The node will emit the tree_exiting signal after running the function, then the tree_exited signal once the node is completely removed.The parent of a node exiting the tree will emit the child_exiting_tree signal.