0 votes

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?

Godot version 3.3
in Engine by (492 points)

1 Answer

0 votes

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.

by (19,278 points)

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.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.