How to add code from _process(delta), from loaded scripts?

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

So I am trying to add code from a loaded gd script. I already can use the functions from any loaded script likeload("res://MyScript.gd"), but how can I use it’s processing function code?

Like in MyScript.gd there is:

func _process(delta):
    print("MyScript code.")

But only loading does not add that print process method to my node. Is that possible to do?

:bust_in_silhouette: Reply From: Ben Humphries

My understanding of your question is that you’d like to execute that print statement once upon your object loading. In that case, you could use the _ready() function that runs once the node has entered the tree for this first time.

func _ready():
    print("MyScript code.")

If you really do need to call the _process() function once, you could do that by calling it from the _ready() function. Note that you will need to pass a delta value.

func _ready():
    _process(1)
func _process(delta):
    print("MyScript code.")

No, the print part is only for implementation, the idea is to import additional process codes from a loaded script into the caller node _process function.

This will open the ability to import script modules to add segmented logic.

The_Black_Chess_King | 2020-05-10 19:53

Yes. Best not to call your function _process :slight_smile: but you can for sure do var my_script = load("res://MyScript.gd").new() and then my_script.do_something(). If you didn’t do the new() to create a new instance then you’d only be able to use the script’s static functions (assuming it had any).

Tim Martin | 2020-05-10 21:19

Ah I see what you’re saying now. Off the top of my head, one way to do that may be to keep a list of type Node and for every node in the list, call a method like “imported_process” if it exists. Then load all of the extra scripts you want into that list and the code in those functions should be executed in the _process() function.

var Nodes : list

func _ready():
    list.append(preload("res://AnyScript.gd").new())

func _process(delta):
    for n in Nodes:
        n.imported_process()

    #rest of _process function below

So then AnyScript would just have to implement that function.

Ben Humphries | 2020-05-11 03:16