Godot 4 custom signal is not emitted when calling a function

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

I have the following class

MyPlayer.gd

extends Node2D
class_name MyPlayer
signal message_printed

func _ready():
	#If I call the function from ready it works
	#hello()
	pass 

func hello():
	print('hello')
	message_printed.emit()

From Mainscene.gd
I create an instance of Myplayer

Then I call the function hello(), (MyPlayer.gd has the hello function)

The hello function prints a message, and emits the “message_printed” signal.

That signal should activate the “hello_test_signals” function, from Mainscene.gd

But it does not execute the hello_test_signals() function

Mainscene.gd

extends Node2D
func _ready():
	var player = MyPlayer.new()
	# here I call the function
	player.hello()
	# And here I connect the signal, but it is never emitted
	player.message_printed.connect(hello_test_signals)
	add_child(player)

func hello_test_signals():
	print('hello_test_signals')

But if I uncomment the hello() function that is in the ready of the “MyPlayer” class, it works.

How can I do so that after executing the hello() function, the signal is emitted and the hello_test_signals() function is activated?

:bust_in_silhouette: Reply From: purple_mage
signal message_printed(variable: String)

message_printed.emit(variable)

then

func hello_test_signals():
    print('hello_test_signals', variable)

im not sure what your trying to do . Both method work i think o_O

From mainscene.gd

I create an instance of Myplayer

my player has the hello function

when the function finishes executing, it emits the signal message_printed.emit()

and from mainscene you should get the signal that was emitted.

and when I get that signal I call the function
hello_test_signals()

but the signal is never sent

however if I uncomment the hello function that is in the ready of the myplayer.gd file

and then I run mainscene.gd if I run the hello_test_signals() function that is triggered by the signal

In other words, it is not activated when I call the hello() function from the mainscene.gd instance.

zkmark | 2023-03-29 01:42

:bust_in_silhouette: Reply From: zkmark

I already solved it, it was because I connected the signal after executing the function

I had to connect the signal before executing the function

mainscene.gd should look like this

extends Node2D

func _ready():
	var player = MyPlayer.new()
	# first i connect the signal
	player.message_printed.connect(hello_test_signals)
	# here I call the function
	player.hello()
	add_child(player)
	
func hello_test_signals():
	print('hello_test_signals')