Connect a buttons signal to a script in a different scene

Godot Version

4.3

Question

So I have a button in a scene from that button I want to send a pressed() signal to my main scene, I have the send scene (the one sending the signal) instanced into the main one

I want them to be able to click a button from the instanced scene and send a signal to the main scene

I want to receive a signal when the button is clicked the problem is the script I want to receive the signal is in a different scene

sorry I explained that terribly

I’m new to Godot so please try make things simple and easy to understand (something I very much failed at :frowning: )

I am very lazy.
Everytime I create a new project, I will create an Autoload called Connect.gd which holds all Signals that I want to use.

# Signal.gd

signal scene_loaded(sceneName: String)

If my scene is loaded, I want to publish this information

# scene.gd
func _ready() -> void:
   Connect.scene_loaded.emit("Tutorial Scene")

And everyone who listens to the signal can then respond

# announcement.gd

func _ready() -> void:
   Connect.scene_loaded.connect(announce_scene)

func announce_scene(sceneName: String) -> void:
   print("Welcome to: ", sceneName)

For your situation, does your scene with the button have a reference to the main scene? For example as a variable?
@export var mainScene
Then you can use the variable to access whatever you want to do.

func _on_button_pressed() -> void:
   mainScene.doThings()

Or do you know that the mainScene is always the parent of the scene you are currently in? Then do this:

func _on_button_pressed() -> void:
   self.get_parent().doThings()
2 Likes

For your case instead use signals i recommend you use groups, so you don’t need to worry about the scene hierarchy:

# main_scene

func _ready():
	add_to_group("main_scene")

func button_was_pressed():
	# do your stuff 
# send_scene

func the_function_that_receive_the_button_pressed_signal():
	get_tree().call_group("main_scene", "button_was_pressed")
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.