I wonder how can I create a script, which contains methods I want to use in multiple scripts. I don't think I want to create a global singleton for it, because I am not storing any global data which will be preserved across multiple scenes. I am having a collection of useful functions nothing else.
GDScript. How to make your own library in Godot and access it from your game scripts
A possible way to create your own library you just create a new script that extends nothing or extends Object
. Use static
keyword in front of your functions.
in my_lib.gd
extends Object
static func my_static_function():
print("hello from my_lib.gd")
in your game script, you can access it using preload
function
const my_library = preload("res://my_lib.gd")
func test():
my_library.my_static_function()
I would give the my_lib.gd a
class_name MyLib
and it would allow calling functions without preloading. Constant variables and static functions are accessible without making an instance of the object. –
Milly looking at Calinou comment i cannot see why for a library you would not use Object, object is the lightest weight and people don't serialize libraries. so i stick with OP reccomend personally –
Indigotin
For future visitors: "Reference" has been renamed to "RefCounted". So now you should
extends RefCounted
(@calinou 's advice is still accurate otherwise; just a naming update) –
Gut © 2022 - 2024 — McMap. All rights reserved.
extends Reference
(orextends Resource
if you need serialization) instead ofextends Object
, as Objects don't perform their own memory management. Unlike Reference and Resource, references to an Object stored in a variable can become invalid without warning. – Faucal