execute the parent's _ready function before the child's

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By jona3717

I have an FSM script and another PlayerFSM. The latter inherits from the former.

FSM.gd

var dict : Dictionary
func _ready():
    for i in get_children():
        dict[i.name] = i
func initialize():
    print(dict["some_name"])

PlayerFSM.gd

extends "res://FSM.gd"
func _ready():
    initialize()

when i run the scene the only function that gets executed is initialize() and it doesn’t print anything.

What if your PlayerFSM.gd’s ready function is as follows to manually call the _ready function of parent first:

func _ready():
    ._ready()#call parent's ready first
    initialize()

godot_dev_ | 2023-04-23 18:54

When I do that, it throws this error:

Error at (6, 6): Expected statement, found “.” instead.

jona3717 | 2023-04-26 16:52

Hmm, I thought calling the parent class’s functions would work (this
post explains a bit on the idea). It might not work because _ready is a built in function. So my next idea I have would be to use a separate function to define your parent’s _ready logic, as follows

FSM.gd

var dict : Dictionary
func _ready():
    readyHook()
func readyHook():
    for i in get_children():
        dict[i.name] = i
func initialize():
    print(dict["some_name"])

and then in the child script, instead of calling _ready, try calling readyHook as follows
PlayerFSM.gd

extends "res://FSM.gd"
func _ready():
    readyHook()
    initialize()

godot_dev_ | 2023-04-26 18:21

Thank you so much! It is a good solution, it adds some more code, but it seems that with ready it will not be possible.

So the function overloading doesn’t allow the parent’s function to be executed. I am curious if there is a function in godot like python’s init that is executed on import.

jona3717 | 2023-04-28 15:31

:bust_in_silhouette: Reply From: jona3717

I’ll mark this as solved, since godot_dev_ provided me with an alternative to the ready call. Thank you!