How to assign a node from another scene to an @export var?

Godot Version

4.2.1

Question

I have a MyScene in my game that only ever gets instantiated by code. When it does get instantiated (which happens a lot), I want a ProgressBar in the main UI to decrement. But, because MyScene isn’t inherently part of the main tree, I can’t seem to do this via @export; I try to assign the value in the inspector, but there’s no way to click on the part of the tree that I need to click on.

I can do this via Nodepath, but for various reasons, it sucks. Is there a way to get @export to behave here?

Thanks for any advice!

Using an event bus singleton is one way to solve problems like this. Create a script that handles global signals, for example:

extends Node

signal my_scene_instantiated(my_scene)

Make it an autoload script (in Project Settings → Autoload). Let’s name it EventBus.

When you instantiate a MyScene node, you can emit a global signal like this:

var scene = my_scene.instantiate()
add_child(scene)
EventBus.my_scene_instantiated.emit(scene)

Connect the signal in your UI or ProgressBar script:

func _ready():
  EventBus.my_scene_instantiated.connect(my_function)

func my_function(my_scene):
  print(my_scene)
  print("MyScene instantiated!")

Edit: Of course, depending on where the scene is instantiated and where you need it, you don’t necessarily need an autoload to handle the signals. But using signals is a good solution whether you make them global or not.

2 Likes

Hey, thanks so much! I’ll be honest, I didn’t know what autoloading was, but this was a good reason to figure it out. Appreciate your help!

1 Like