+1 vote

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!

Godot version 3.4.4.stable
in Engine by (30 points)

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

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. :)

1 Answer

+2 votes
Best answer

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.

by (21,864 points)
selected by
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.