`I recently had the need for some of my child nodes of certain scenes to have to have access to the LevelRoot scene which holds the code that handles the gameplay.
I started to inject my LevelRoot scene in the children nodes that require the info and on setup it starts everything.
Basically on ready in LevelRoot i set a variable called level root found in a child node elsewhere and I set it to self. I do this to get access to the functions and information of the main node LevelRoot.
My main question is whether this type of code setup is a good thing.
In Godot, it’s adviced to call down, signal up.
In your case, that would mean LevelRoot can directly call function on its child nodes, but those child nodes cannot call functions on LevelRoot. Instead, they would emit signals that LevelRoot is connected to.
There are very valuable info on that topic you can get here: https://www.reddit.com/r/godot/comments/y2jovs/as_a_new_dev_what_is_meant_by_call_down_signal_up/, the most important benefit, imho, is that it decouples he nodes and makes the child nodes reusable.
Now, to talk about your current pattern: it’s not a completely invalid pattern, however it comes with both pros and cons. To know if using such a code structure is a good thing, you should know about them and decide depending on your project and your needs.
Here’s what I’m thinking of:
Pros:
Having all your logic in LevelRoot makes the gameplay code centralized.
Since the assignment of LevelRoot in all child nodes is done manually (instead of using some get_parent() as LevelRoot logic in all children), you have more control over when the assignment is done, which reduces the errors you’ll get from nodes execution order.
For a short term project, that’s a fast and efficient gameplay implementation.
Cons:
Obviously, since you have one node that functions are shared by many other, you have a very tight coupling, which one would tend to avoid in programming. Say you’re changing a function, then, you’d have to be absolutely sure that every child node that’s calling this function will not have its behaviour broken.
You cannot test your child nodes in isolation, since they work only with LevelRoot.
For a long term project, that would probably mean LevelRoot will become an enormous code with tons of functions, which is not ideal.
TL;DR: this approach is not uncommon, but it’s only fine as long as your project is small. If your game gets bigger and bigger, you’ll find it more troublesome than convenient to work with such a code structure. In such a scenario, the first thing you’d want to do is reduce the coupling between the root node and the child nodes, by using signals.
This helped me out a lot. Thank you I will have to do more research on that and study a bit. But now at least I have a general outline on that programing aspect.