I want to set the script for a node via code. I have assumed that set_script() is doing this but it does not work in my case.

const script = preload("res://path_to_script.gd")

func call_script():
	get_node(path_to_node_to_which_script_shall_be_attached).set_script(script)

Do I miss something? Do I have to "start/load" the script after I have attached it to the node?

What do you mean does not work? Did you try single step in debugger and check any errors?

There are no errors. If I call get_node(path_to_node_to_which_script_has_been_attached).get_script() afterwards, everything seems fine (function returns the correct Object ID of that script). But the functions inside that script do not "start".

Assume, that the script holds a func _process(delta), which only purpose is printing out "some text" to console (print("some text"). But after I have attached that script to the node, that print("some text") won't happen. Seems like I have to press some "Activate the script" Button after attaching that script?!

I hope that makes sense, what I have tried to explain.

Hi Is the script the child of the node involved? Just a thought...

6 days later

No, it is not attached to the "direct" child. I try to explain this in some "ascii art diagram"

child_script_setter = node which sets/invokes the script child_script_getter = node which the script is attached to

parent ---------> child_script_getter | |-----------------> child_node ------> child_script_setter

Does that make sense?

2 years later

If this node does not have a "_process" function, then you need to activate it with "set_process(true)"

3 months later

In case someone else is facing this problem when creating a node and assigning the script in code: the answer above works, node.set_process(true) did the trick.

2 years later