How to bind variable after entire scene has loaded

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

In GDScript, I have the following issue:

*. I create a component, call it Maker which uses a common instance of the component Inventory.
*. I have a top level scene, MakerHarness, for exercising Maker. MakerHarness contains an instance of Inventory and an instance of Maker.
*. I have another top level scene, TheGame, which contains a common instance of Inventory and many instance of Maker.

  • I want Maker to call Inventory functions.

Is there a best way to do this? Here’s what I’ve tried:

Option 1: AutoLoad as a singleton

I create a project wide Project Settings/AutoLoad with an Inventory instance. I use this to call functions anywhere.

  • Means that the Inventory scene must always be in a working state before I can do any other development.
  • As I have other classes, there will many scenes that must compile and load correctly before any other work can be done.
  • Can call is normally, e.g., Inventory.add_item(...)

Option 2: AutoLoad a global singleton named g.

I create a scene that just has instance variables, e.g., var Inventory. In both MakerHarness and TheGame, in the _ready(), I do g.Inventory = $Inventory.

  • I don’t see explicit documentation about the order of AutoLoad instantiation
  • I can create mock in the global. The mocks would be used unless real classes are explicitly set. This allows me to write complex code in any order.
  • Only slightly clunky to call. It needs one line per singleton in each harness or top level’s _ready() function. Calls in other code are just an indirect: g.Inventory.add_item(...).

Option 3: Use a global signal

I haven’t tried this, but it seems like I could have a global singleton that can emit a signal ApplicationReady to handle processing deferred until the entire application is ready.

  • I pass any global references as signal parameters.
  • Receiving handler has code like Inventory = params["Inventory"] and items are called naturally like Inventory.add_item(...)
  • Cannot connect the signal from the gui, must call connect() from each component’s _ready().

With Godot there always seems to be more. Is there a better way I just don’t know about? Has anyone done the Option 3?

:bust_in_silhouette: Reply From: Gluon

Well personally I use global autoload scripts for quite a few things, I have one for various functions and another separate autoload script for shared variables. I cannot say that is necessarily the best but it certainly works.

One simple thing I can mention though I think it is likely you are aware of this but do you know that there is an onready function in the godot scripts?


Onready var example = true

this will ensure that the var will not be created until the node has been fully instantiated.

Thank you for your comment.

CharlesMerriam | 2022-05-21 18:06