+1 vote

Could we create a class which works as a singleton but only in one scene? Sometimes I feel it is too local to make it autoloaded, but I could not find any other way. Thank you for your time!

Edit: one way to do this is using resource. Write one class GlobalClass extending resource, which has every variable and methods you need. Then make one resource file (.tscn) using this code, and attach it to every node which will use it (e.g. add a line export(Resource) var global_class = global_class as GlobalClass and set the resource file in inspector). I should note that resources are passed by reference.

If I have to list Cons of this method based on my limited knowledge, I would say:

  1. Resources cannot receive signals directly.
  2. I need to remember which node is an actual global node. Otherwise, any attribute can be changed accidentally (in other words, it seems really dangerous).

I really appreciate it if you could share any other way!

Godot version 3.5.1
related to an answer for: How to use singleton in godot?
in Engine by (46 points)
edited by

1 Answer

0 votes

Very good question...

There are several ways to do something similar, such as having a node called "gobal" containing the variables you want to use, or employing some event system into a singleton that stores (and send) data knowing from which scenes this data arrives.

by (24 points)

I considered making a global node in a scene, but I am not sure how it works. We cannot get the node in _ready() unless it is a child. A node cannot be a child of every node in a scene, right?

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.