How to connect the signal of the button with two different scene?

Godot Version

4.2.1

Question

I want to press a button in scene A, then switch to scene B, and have scene B receive the signal of the button pressed in scene A and print something.

##script

button in A_Scene:

extends Button

signal join_pressed

func _on_join_pressed():
emit_signal(“join_pressed”)
get_tree().change_scene(“res://b_scene.tscn”)


B_Scene:

extends Node2D

func _ready():
get_node(“/root/main/join”).connect(“join_pressed”,_on_join_pressed())

func _on_join_pressed():
print(‘hi’)

First of all, in Godot 4.2, it has been changed from

get_tree().change_scene()

to

get_tree().change_scene_to_file(path: String)

[Look here](SceneTree — Godot Engine (latest) documentation in English

Secondly, when you change a scene, the current scene is removed from the tree. Since scene A with the button is no longer running, you can’t receive a signal from it. [Read more here](https://Note: Operations happen in the following order when change_scene_to_packed is called: The current scene node is immediately removed from the tree. From that point, Node.get_tree called on the current (outgoing) scene will return null. current_scene will be null, too, because the new scene is not available yet.)

I think having a scene manager will work best for what you want to achieve. A scene manager is just an autoload script that is responsible for changing the scenes. Since it is always running, you can call any function in B_Scene after it is loaded.

1 Like

Thanks a lot man!
Btw how to get the scene manager?Is that from AssetLib?

No. It’s just a script set as autoload in your project settings. Check for autoload in the Godot docs.

Once you set the script as autoload, you can call it from anywhere.

1 Like