Can you split a class across multiple files in GDScript?

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

Hopefully I can explain this correctly, as I’m still pretty new to Godot. Basically, I want to have a class, for example in res://scripts/class_test.gd

In this class, there will be several methods, and some of them will have a lot of code associated with them. So what I’d like to do is have class_test.gd include this:

class_name MyClass

And then possibly some virtual functions. Then, in separate script files, such as class_test_func1.gd, class_test_func2.gd, etc. have each of these functions actually defined. (again, I anticipate the functions being extremely long and having multiple branching if/else statements, so like probably 200-300 lines of code per function.

I know I have done something similar a long time ago in c++ to make the code easier to read, because I could just open that specific script instead of searching through like 8000 lines of code to find what I was looking for.

Would loading the other scripts with something like:

var thing = load("res://scripts/class_test_func1.gd")
var myThing = thing.new()

Is this even possible? Is it a good idea? As far as what I’m trying to accomplish is working on an FSM and having the states be handled by different files so it’s easier to maintain when I’m working on one specific state. Thanks in advance for any help or advice!

:bust_in_silhouette: Reply From: Zylann

You can’t really split the same class as multiple files and still expect it to be the same class. To keep it exactly the same class, you really would end up with 8000 lines in the same file. In C# there is the partial keyword to do this, but it doesn’t exist in GDScript.

However you can split code in multiple files using static functions:

class_test.gd

const Function1 = preload("class_test_func1.gd")
const Function2 = preload("class_test_func2.gd")
const Function3 = preload("class_test_func3.gd")

func func1():
	Function1.func1(self)

func func2():
	Function1.func2(self)

func func3():
	Function1.func3(self)

class_test_func1.gd

static func func1(me):
	print(me.member_var)
	# A huge amount of code [...]

This might even be good to do this because instead of having 8000 lines of code that can potentially access the same member variables (and it gets more horrible to maintain with virtual functions), you can restrict what each function can actually access to.

If the amount of code is what bothers you for doing a state machine, I would actually consider making each state a separate class, rather than a separate function. You could then build a state machine quite easily by having a parent node containing the shared variables (accessed from states using get_parent().variable), and multiple child nodes each being a separate state.