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:

extends Resource

func do_something():

extends Node2D
const CHARACTER_FUNCTIONS = preload("res://scripts/")

@onready var character_functions =

func something_else():

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:

static func do_something():

const CHARACTER_FUNCTIONS = preload("res://scripts/")
func something_else():

This way you won’t be instantiating the 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