How to split functions into different files?

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

My main file is getting quite big with lots of functions. I’ve started to create new .gd files that extends Resource and load them into the main file. I don’t know if this is the “right” way or if it is bad for speed or something. Do you know a better way?

Here’s an example:

# character-functions.gd
extends Resource

func do_something():
	pass

# main.gd
extends Node2D
const CHARACTER_FUNCTIONS = preload("res://scripts/character-functions.gd")

@onready var character_functions = CHARACTER_FUNCTIONS.new()

func something_else():
	character_functions.do_something()

See also this question about making gdscript utility classes.

idbrii | 2023-06-22 15:00

:bust_in_silhouette: Reply From: a_world_of_madness

Godot is really supposed to be used with nodes, maybe you could separate functionality from the main script to multiple sub nodes. But without knowing more about what your main and character-functions actually do, you could extend nothing instead of extending Resource, and make the functions static:

# character-functions.gd
static func do_something():

# main.gd
const CHARACTER_FUNCTIONS = preload("res://scripts/character-functions.gd")
func something_else():
    CHARACTER_FUNCTIONS.do_something()

This way you won’t be instantiating the character-functions.gd class at all, you are just calling the static functions from it.

If the script functions cannot be static, you should extend RefCounted instead, since it’s the simplest class that does memory management for you (gets freed from memory when no longer in used / in scope). Resource is the base data-container class, so it’s otherwise identical to RefCounted, except it includes functionality to save itself to the disk. See the When and how to avoid using nodes for everything documentation page for more info about these classes.

Thank you very much. I’ll use the static function then and not instantiate the script. That’s mainly for functions that return something or change a value.

Nottblod | 2023-06-12 15:29

1 Like