Onready vars introduced through set_script() are all NULL

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

I am writing a function that briefly introduces a script to the tree by creating a node and setting the script. While I am able to access regular variables via set_script(), any onready variable I try to access is never assigned (null).

How do I access onready vars using set_script()? There are some variables in these scripts that need to be onready, so I want to have a way to access them without always having these scripts active (I only want them instanced when they are relevant).

Below is a simplified version of my code to help illustrate my issue:

Instanced_Script.gd

var works = "This variable can be accessed and does not show up as NULL"

onready var doesnt_work = "This variable can't be accessed and instead shows up as NULL"

Main_Script.gd

var crashes_on_assign: String

var scriptNode = Node.new()
add_child(scriptNode)

var variableScript = load("[address of Instanced_Script.gd]")
scriptNode.set_script(variableScript)

print(scriptNode.works) #prints the string as expected
print(scriptNode.doesnt_work) #prints "Null"
crashes_on_assign = scriptNode.works #crashes with error (typed below)

#...the code continues but is not relevant to the issue...

ERROR: Trying to assign value of type ‘Nil’ to a variable of type ‘String’.

Any help would be appreciated. Thank you!

What happens if you assign the script before you call add_child()?

jgodfrey | 2022-06-06 14:47

That works! I didn’t know you could do that – I assumed that would be like giving a script to a node that doesn’t exist, but I guess it’s more like giving a script to a node that exists, but hasn’t been added to the tree.

Thank you so much for the help! This had me stumped for a few days. :slight_smile:

358JH33E | 2022-06-06 14:56

:bust_in_silhouette: Reply From: jgodfrey

Converting the above conversation to an “Answer” for future reference by others…

As noted above, the solution was to add the script to the new node before calling add_child(). I assume that’s because the call to add_child() ultimately triggers the setting of onready vars when the node is fully initialized.

Waiting to add the script until after the node has been added to the tree does not trigger the setting of onready vars.