Set script for node in code (set_script method) when constructor takes arguments.

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

Hi, is there any way how to attach script to a node (in code) when the script constructor takes arguments?

Thanks for the answer.

:bust_in_silhouette: Reply From: SteveSmith

You would just add it the normal way. Adding a script to a node doesn’t directly run the functions in the script.

Hi, that is not true. According to documentation “If the object already had a script, the previous script instance will be freed and its variables and state will be lost. The new script’s _init method will be called.” I just don’t know how to make it so I can call _init with parameters.

Karol23 | 2023-01-23 08:41

Thanks, you are correct.

One solution is to give your init params default values?

SteveSmith | 2023-01-23 09:20

Yes, that’s one solution. Or just have empty constructor and set variables on the next line. There are solutions how to avoid the problem. But all of them I think deny the primary point of constructor - to ensure that user always has to provide all required parameters.

Karol23 | 2023-01-23 09:35

I think the problem stems from the fact that normally, when adding a script to a node (e.g. via the GUI) the user doesn’t have any way to pass params to a constructor.

A few other alternatives:-

  • You could create your own “myinit()” method which the user must call after the script has been added, with params. Show a warning or something if this method hasn’t been called by the time _process() is called, or something.

  • Instead of adding a script, have a default script which accepts and uses an instance of another class. The user must create an instance of this class (with constructor params) and pass it to the script.

SteveSmith | 2023-01-23 09:51

Thanks for the good suggestions. Do you think it’s missing feature worth reporting?

Karol23 | 2023-01-23 10:12

I’ve personally never needed to add params to a script when adding it as a node. What are you wanting to achieve?

SteveSmith | 2023-01-23 10:21

I have a custom MapObject class. And I have loaded scene instance containing Node3d with model. And I want to extend the model scene with the MapObject class so I can have addional data like model size (in map coordinates) etc. All created in code.

Karol23 | 2023-01-23 10:37