How to access a changing variable in child node?

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

If the root node is KinematicBody2D, and the character has a child node stats storing all the variable root node use, like speed. After the KinematicBody2D node enter the scence tree and get stats 's speed, if the speed changed in child node stats , dose it have to send signal to inform the KinematicBody2D node to change its speed variable so the KinematicBody2D node can move in a different speed?

:bust_in_silhouette: Reply From: TheFamousRat

Hello hsjaaa,

You could do it with signals yes.
To accomplish this, you should only ever modify the node’s stats (among which, speed) with a dedicated method like “set_speed(value)”. You could emit the signal from there.
So something like that :

func set_speed(newSpeed : float) -> void:
    speed = newSpeed
    emit_signal("speed_changed", newSpeed)

Something like that should work. Of course you should do a line like that somewhere earlier in the code :

nodeThatContainsTheStats.connect("speed_changed", theKinematic2Dnode, "methodThatGetsCalledByTheSignal")

Hope this helps

Thanks, it’s helpful!

hsjaaa | 2019-02-09 11:59

:bust_in_silhouette: Reply From: Dlean Jeans

I think a signal would be unnecessary if you use it like this from the root node:

extends KinematicBody2D

func _physics_process(delta):

I tried this, it works, but is this good practice? Since it call child node every frame.

hsjaaa | 2019-02-08 04:08

1 Like