I
Irisss_54

_ready function and Onready variable

As far as I comprehend, the Onready variable is for storing the path to a node inside a variable (not quite sure). However, I am confused with the _ready function.

What's the actual function of it? What's the difference between _ready and other functions such as print function (to print out text) and _process? In order to print the results of the function of the nodes, we must use _ready?

As it is written like this:

func _ready( ) -> void:

    add_row("Athos")

    add_row("Portos")

    add_row("Aramis")


  • Nathan Lovato replied

    The onready keyword delays running a line of code until the start of the _ready() function. It's a small convenience feature, because we very often need to store nodes into variables, but in older versions of Godot, we had to do this all the time:

    var scoreboard

    func _ready() -> void:
        scoreboard = $Scoreboard

    With onready we can do the same thing on one line of code.

    onready var scoreboard = $Scoreboard

    In practice it's as you wrote: we use it to get nodes and store them in variables. The important take away is that every line with onready gets the node at the start of the _ready() function.

  • Nathan Lovato replied

    _ready() is a function that Godot calls at a specific point in time: when a node gets added to the scene tree. Writing code in the _ready() function guarantees that this node is in the scene tree and that all its children also are in the scene tree, allowing you to manipulate child nodes in code.

    This is why we must get nodes in the _ready() function (or using the convenient onready keyword). There are other places in our code where trying to get a node would result in an error.

    The way to see _ready() is that it's a good place to initialize my node and initialize its child nodes if needed.

    1 love
  • I
    Irisss_54 replied

    I see! Thanks Nathan!