Autoload vs path-based global access

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

Sometimes one needs to get some node accessible from different places: global settings, networking code, utilities for changing scenes. One can either set these nodes as autoload and use them as singletons, or instantiate them in a fixed path under root and access them as: get_node("/root/globals/networking").

What are pros and cons of using one vs the other? Do these two actually differ at all?

:bust_in_silhouette: Reply From: Inces

The main difference is, that hard coded root will not make it easy for You to test separate game elements by opening their own scene. It is enough of a problem for everyone to use Autoload instead. But Autoload does have some serious drawbacks : it doesn’t have access to tree and viewport general functions ( like get nodes in groups or create dynamic timer ), it has a tendency to crash due to too much code scripted , it can’t use .tscn files, only uses .gd files .

:bust_in_silhouette: Reply From: zhyrin

Additionally to Inces’ answer, I would say the “cleanest” solution used in software projects is dependency injection. It’s somewhat finicky to implement in godot, but that is a very clearly documented way to see what dependencies your script/scene has. It also makes it a lot easier to test.

An idea I’ve been toying with is extending SceneTree with a class that has access methods for nodes my scenes would commonly access. If you formulate the architecture correctly, this could replace both autoloads and “global get_node() based” access.