McAwl / Explosional

MIT License
2 stars 0 forks source link

Decouple scenes as per best practice #145

Open McAwl opened 2 years ago

McAwl commented 2 years ago

Scenes operate best when they operate alone. If unable to work alone, then working with others anonymously (with minimal hard dependencies, i.e. loose coupling) is the next best thing.

Various methods for this, eg use of signals:

See https://www.gdquest.com/tutorial/godot/best-practices/signals/

Eg HOW WE USE SIGNALS

At GDQuest, we use signals mainly in two cases:

When we need another node to react to a specific, one-time event. For example, a took_damage signal that gets emitted when a character loses health. When we need a UI element to constantly update based on a game entity’s value changes. Most of the time, we don’t want the UI to store a reference to nodes in the game world and directly access their properties.

McAwl commented 2 years ago

Also see advice on parent, sibling and child behaviours. Basically children should not be hard coded to the patent API, so they can be reused and more predictable.

From https://docs.godotengine.org/en/stable/tutorials/best_practices/scene_organization.html

"If at all possible, one should design scenes to have no dependencies. That is, one should create scenes that keep everything they need within themselves. If a scene must interact with an external context, experienced developers recommend the use of Dependency Injection. This technique involves having a high-level API provide the dependencies of the low-level API. Why do this? Because classes which rely on their external environment can inadvertently trigger bugs and unexpected behavior.

To do this, one must expose data and then rely on a parent context to initialize it" by eg:

1 Connect to a signal. Extremely safe, but should be used only to "respond" to behavior, not start it. 2 Call a method. Used to start behavior Etc etc Common to these: These options hide the points of access from the child node. This in turn keeps the child loosely coupled to its environment. One can re-use it in another context without any extra changes to its API.

From https://www.gdquest.com/tutorial/godot/best-practices/signals/ "It takes 2300 signal emissions and related delegate function calls to consume 1ms of processing time on the main thread on my machine. " so many many signals can be used.