Is there a way to call a function that is inside a script not connected to a node?

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

I have a solitary script full of functions that I want to call, but I do not know how to do it.

What do you mean by “Solitary script”? How does your project look like? It is not on a node? Does it contain just static functions?

Zylann | 2018-11-30 18:12

The script is not tied to any node, so I called it solitary. No, it has no static functions.

JulioYagami | 2018-11-30 19:12

:bust_in_silhouette: Reply From: p7f

Hi,

I you can do it with preload and load. For example, your script is script.gd:

func _init():
    #do constructor stuff if needed
    pass
func hello():
    print("Hello")

And then you instantiate it from a node:

extends Node2D
func _ready():
    var script = preload("res://script.gd").new()
    script.hello()

Do i explain myself?

Note: edited my answer thanks to @Ruckus T-Boom and @Zylann comments.

It doesn’t have to be a class. Any script can be loaded and used (so you don’t need the _ready function in your script.gd or any sort of extends), you can have libraries of “static” functions.

Ruckus T-Boom | 2018-11-30 18:07

In order to use script.gd the way you described, you would need functions inside it to be declared as static.
Otherwise, you have to make an instance of it, like so:

var script = preload("res://script.gd")
var instance = script.new()
instance.hello()

The reason is, scripts are both classes and resources. It means that when you do load or preload on a script file, what you get is the class itself. Then you can use that class to either call static functions, or make instances of it.

Note: if you make instances with new(), indeed there is no reason to implement _ready() because that function is only called on scripts extending Node classes, after they enter the tree.
On the other hand, if your script is a plain class that doesn’t extend anything, you can implement _init(), which acts as a constructor.

Zylann | 2018-11-30 18:14

Interesting, it seems to work just fine without static so long as you don’t access any members, though the terminal does give a warning “Can’t call non-static function”.

Ruckus T-Boom | 2018-11-30 18:22

yes, It works just as i answered, cause i tried before posting answer. However, if it’s not best practice of if it wont always work, i must edit answer. Did not have to create instance either to run hello. Is that not expected?

p7f | 2018-11-30 21:04

if i do an instance like

var instance = script.new()

shouldn’t i then run

instance.hello()

instead of

script.hello()

?

p7f | 2018-11-30 21:08

Yes, my bad, I corrected it

Zylann | 2018-11-30 21:15

Edited my answer thanks to your comments. is it better now?

p7f | 2018-11-30 21:17