Signalling one scene to instance another

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

This is probably quite a basic question, but I haven’t quite figured it out.
I have a bunch of different scenes that represent each of the different scenes in a game. What I want to do is instance the main menu under “main”, and when it signals something (like “play”, or “options”) the menu will play a closing animation, free, and then instance the relevant scene under main. How do I go about doing this?

Essentially I need to find a way to connect a signal from a scene to the main scene, but only when it’s been instanced by code, before the game has started, none of the scenes are connected to each other.

:bust_in_silhouette: Reply From: njamster

Main.gd

extends Node

signal play

var main_menu_scene = preload("<PathToScene>.tscn">)

func _ready():
    var main_menu = main_menu_scene.instance()
    self.connect("play", main_menu, "_on_play")
    add_child(main_menu)

    # wait 5 seconds before emiting the signal
    yield(get_tree().create_timer(5.0), "timeout")

    emit_signal("play")

MainMenu.gd

extends Node

func _on_play():
    # TODO: play closing animation
    # TODO: instance new scene
    # TODO: free this scene

No real need to use signals for that though, you could directly call _on_play here.

Thanks, this is quite useful. How might I go about it the other way around? For example, if from the main game, you might might need to go back to the main menu, or to the options menu or something like that? How might I connect a signal the other way around?

psear | 2020-06-13 17:08

After you instance the main_menu-scene in Main.gd, do this:

main_menu.connect("go_back", self, "_on_MainMenu_go_back")

Then when you emit the go_back-signal in MainMenu.gd, the function called _on_MainMenu_go_back in your Main.gd will be called.

njamster | 2020-06-14 16:40