Adding singleton/ autoload scenes from GDScript in run-time

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

I am working on a game collection launcher. I have 10 existing games with Autoloaded singletons. I plan to add more in future.
I import existing games through .pck (ProjectSettings.load_resource_pack(…)), but imported games need their own singletons.

1, How can I add autoload singletons after the game (collection launcher) started?
Adding nodes to root won’t make the node visible in global scope variables. (cannot access the singleton by its name)
2, Is there any way to add global scope variables?

No details about this in documents:
(Exporting packs, patches, and mods — Godot Engine (stable) documentation in English)
Singletons (Autoload) — Godot Engine (stable) documentation in English

Thanks.

:bust_in_silhouette: Reply From: MintSoda

Create an EditorPlugin, use its add_autoload_singleton().

Thanks.
It is good in Editor. I am looking for a solution after the game started and running.

DavidPeterWorks | 2021-09-03 05:37

:bust_in_silhouette: Reply From: DavidPeterWorks

My findings is that it is not possible to add singletons after the game started and running.

I solved that like this:
1, create placeholder/dummy singletons manually in editor before the game started.
2, Import the resources/scriptis with ProjectSettings.loadresourcepack(…) in runtime.
3, replace all singletons’s script with set_script(…) in runtime.

This requires planning. Singleton names and paths must match.

:bust_in_silhouette: Reply From: Iftah

Not really an answer to your question but maybe a “good enough” solution - I think it is easier than calling set_script

  1. create a single autoloaded singleton with fields holding the real singletons. Initially set these fields equal to null:

    # in singletons.gd    ## autload this file
    var GAME = null
    var ECONOMY = null
    var NETWORK = null
  1. in runtime, when initialize the fields.
    eg. load Game.pck file…and then
    Singletons.GAME = Game.new()

  2. in the other files you can use Singletons.GAME directly, or initialize a field for easy access. Of course, you need to make sure to use it only after it was initialized.


    # eg, in enemy.gd
    var GAME = Singletons.GAME
    GAME.enemies += 1

That is a good idea. I will try that later.
Thank you.

DavidPeterWorks | 2022-08-15 07:15