Get random-value from child-variable

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

Hi everyone,

there’s a random value created in a Sprite node’s script

rng.randomize()
var a_random_number = rng.randf_range(8, 18)

Now a parent wants to grab that value

var the_grabbed_random_value = $Sprite.a_random_number

but this thows the error

Invalid get index 'a_random_number' (on base: 'null instance').

How can I grab such a variable’s value from a child node?

:bust_in_silhouette: Reply From: jgodfrey

So, the issue here is that your $Sprite reference isn’t working - it’s null according to the error. What node is the above script associated with? For that $Sprite reference to be valid, you’d need a node named Sprite as an immediate child of the node associated with the above script. Apparently, that’s not the case here.

An immediate child, you say… it’s a grand-grand-child, so perhaps that’s the issue? For some reason I thought that any children down the branch would be “found automatically” in such a situation.

EDIT:
I think I know my mistake now: following the variable scope I shouldn’t put my var a_random_number into the func _ready(): (or any function really) because the value would be erased immediately after the reday-script finishes, thus leading to the null-instance. Putting the variable “on top of the script” should keep the value available.

pferft | 2022-10-29 09:49