Here I have this simple setup: a state machine node and child state node.
State machine knows of its parent, and that value must be passed into a child state too.
And here I found that it may be tricky. And I do not exactly understand it, and I think it depends on some hidden order of things being ready as the tree is built...
This works:
- Passing value to child from parent's _ready()
@onready var abilityOwner : BaseUnit = get_parent()
func _ready() -> void:
for child in get_children():
if child is AbilityState:
child.unit = abilityOwner
- Calling 'tree' from a child
@onready var ability : Ability = get_parent()
var unit
func _ready() -> void:
unit = ability.get_parent() # v.1
#unit = get_parent().get_parent() # v.2
This doesn't work (returns <null> reference):
- Directly assigning parent's variables
@onready var ability : Ability = get_parent()
@onready var unit : BaseUnit = ability.abilityOwner # v.1
# OR v.2
# func _ready() -> void:
# unit = ability.abilityOwner
- Making a function in parent and calling it
class_name Ability
@onready var abilityOwner : BaseUnit = get_parent()
func get_ability_owner():
return abilityOwner
class_name AbilityState
@onready var ability : Ability = get_parent()
@onready var unit : BaseUnit = ability.get_ability_owner()
# Would be same in ready
# func _ready() -> void:
# unit = ability.get_ability_owner()
I do not exactly understand why it works like this. To me it seems that the tree itself is ready and built way before all the variables and functions inside the Nodes. Am I right in this?..
PS: I kinda really tried to bug-proof this, removed all type declarations just in case, copypasted all names, got no errors on run, would be very ashamed if I missed something like that... But I think I did not.