After setting script using set_script(), how to access script's methods?

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

Hello I have the following code:

var checkpoint = Area3D.new()
var script = load("res://Scripts/Checkpoint.gd")
checkpoint.set_script(script)

checkpoint.nth_checkpoint = n
checkpoint.body_entered.connect(_on_Area_body_entered)

I try accessing the method _on_Area_body_entered which is defined in the Checkpoint.gd script, but I get the following error:

res://Scripts/Editor/TrackGenerator.gd:66 - Invalid get index ‘_on_Area_body_entered’ (on base: ‘Area3D ()’).

I also tried directly calling methods from the script, and it gave similiar error. I know this is because it’s trying to find it from the Area3D class, but I don’t know how to access the script’s methods in this manner. Trying to use the methods from the script variable doesn’t work either.

checkpoint.body_entered.connect(**_on_Area_body_entered**)

I think this is a reference to the local script, the one running the code (TrackGenerator.gd). If you want to connect signals in checkpoint then calling set_script will call the script’s _init method where it’s probably better to connect things up.

spaceyjase | 2023-05-10 10:22

I forgot to mention I’m using a @tool script, so I think _init won’t display in editor, although it will work when launching the scene. This will work for now, thanks!

I was wondering, if it’s possible to fire _init or something similiar when creating in the node in editor

zantze | 2023-05-10 10:49

If the other script (checkpoint) is also marked as a tool script, it should fire in the editor; everything you want to run in the editor should be marked as tool. I believe other methods are also fired if, say, when adding to the tree. You can always create your own init-like methods (say, start?) and call them via the tool script.

spaceyjase | 2023-05-10 11:38