Godot 3 - How to make a action between scenes with signals?

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

Hi, lets say I have 2 scenes: scene A and scene B. A has a node called Press. And B has a node called Print. So I want to print a string with the Print node every time i press the right key in Press.

I have tried this:

Code for Press:

extends Node

signal printOk

func _ready():
	pass

func _process(delta):
	if Input.is_action_pressed("ui_right"):
		emit_signal("printOk")

Code for Print:

extends Node

func _ready():
	pass    

func _process(delta):
	connect("printOk", self, "_on_print_number") 

func _on_print_number():
	print("You pressed the right arrow key")

Thanks.

:bust_in_silhouette: Reply From: SingingApple

Instead of having two scenes for the two nodes, I would recommend you to have one scene with the following structure:
-Main
----Print
----Press
But if you DO need to have two different scenes, then you can create a third scene ‘Main’ and add the two scenes ‘Print’ and ‘Press’ as its child through instancing in the same way as the tree shown above.
And then you can,
Replace the code for Print with this:

extends Node

func _ready():
    #don't do this in process instead do it in ready
    get_parent().get_node("Press").connect("printOk", self, "_on_print_number") 

func _on_print_number():
    print("You pressed the right arrow key")

The code for press can remain the same but I do think that code is a bit inefficient.
Hope this helps.

This is just a hypothesis to understand how to use signal between scenes. Thank you.

arthurZ | 2018-02-17 16:49

:bust_in_silhouette: Reply From: hilfazer

This line

connect("printOk", self, "_on_print_number") 

will try to connect printOk signal of Print object with its _on_print_number function.
It won’t work because this signal is in other script.

Where to call connect() depends on whether or not one of your nodes has a reference to another and how are those nodes positioned in relation to each other.

If, for example, Print has a reference to Press you can do this in Print’s code:

pressObjectReference.connect("printOk", self, "_on_print_number") 

If scene A is a parent of scene B you can do this in Press code:

connect( "printOk", get_node("Print"), "_on_print_number" )

And if you have another scene that parents both scene A and B you can do this in that scene’s code:

get_node("Press").connect( "printOk", get_node("Print"), "_on_print_number" )

There are other options but in any case you need to call connect() from a place that knows of both your nodes.