|
|
|
|
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?
if i do an instance like
var instance = script.new()
shouldn’t i then run
instance.hello()
instead of
script.hello()
?
Yes, my bad, I corrected it
Zylann | 2018-11-30 21:15
Edited my answer thanks to your comments. is it better now?