Trouble understanding class structure

Godot Version

4.4.1

Question

I do not understand how to structure a class in Godot

I recently tried to add some test from the GDUnit addons and I realized my class couldn’t really be initialized.


Here is the main class of my game playedGame which is pretty much an abstract class (yes I know it’s coming in next release) it has most of the logic to make my game work, the subclasses being the different types of game modes. All using the parent’s logic to work.

But when trying to make a new PlayedGame I realized I can’t because it depends on those children nodes but if I remove those children nodes then the game can’t really make sense because the game mode needs a camera and a background ! The other two nodes could be made in code but it’s more readable this way.

What I am really asking here is how to manage graphical component and code component. Should I separate it entirely ? Should I do this approach which well, works, but makes it so that the only way to instance my class is to call its resource ?

I’m really confused about the best practice and if there even is a clear way to solve this problem.

Thanks !

That’s exactly why scenes exist. If for some reason you can’t load the resource for it at runtime, you can make a static function in PlayedGame that instantiates its scene and returns the node:

# the script attached to "playedGame"

const played_game_scene: PackedScene = preload("path/to/scene")

static func create() -> PlayedGame:
	var played_game: PlayedGame = played_game_scene.instantiate()

	# set up played_game if needed

	return played_game
1 Like

Hey, sorry to bother even tough I marked this as solved but I was wondering about overriding new() or _init(), because _init() does not load anything and for new() it just refuses. To use this I have to create a method not already supported by the engine right ?

I feel like it would be nice being able to override _init() to be able to do PlayedGame.new(argument1, argument2) but I guess it’s possible with init()

It’s a common programming pattern called Factory Method (or a slightly more complex Builder Method) to use a custom constructor for a class instead of overriding the existing one. I use it all the time.

1 Like