6

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.

Andrey Kachow
  • 936
  • 7
  • 22

1 Answers1

10

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()
Andrey Kachow
  • 936
  • 7
  • 22
  • 8
    It's generally [recommended](https://docs.godotengine.org/en/latest/getting_started/workflow/best_practices/node_alternatives.html) to use `extends Reference` (or `extends Resource` if you need serialization) instead of `extends 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. – Calinou Jul 27 '20 at 07:15
  • 3
    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. – NeZvers Jan 18 '21 at 14:18
  • 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 – Richard Nov 15 '22 at 14:41