How to make a singleton in one scene

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

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!

:bust_in_silhouette: Reply From: yosoyaquel

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.

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?

toxicvgl | 2022-10-23 17:29