+1 vote

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?

Godot version v4.0.stable
in Engine by (142 points)

2 Answers

+2 votes

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 .

by (8,099 points)
0 votes

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.

by (1,611 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.