Signal, connect, instantiate, oh my

Godot Version

4.2

Question

If have a door scene with a signal:

extends Area2D

signal player_entered(description)

func _ready():
pass

func _on_body_entered(body):
if body.name == “Player”:
player_entered.emit(“they’re here”)

func _on_player_entered(description):
print(description)

In my tilemap node I instantiate a door

var d = door.instantiate()
add_child(d)
d.player_entered.connect(_on_player_entered)

which means I need a function in the tilemap node that is the same as the door node:

func _on_player_entered():
print(“this never prints”)

What am I missing here? The “they’re here” prints out, but “this never prints” doesn’t. Why does a custom signal function have to exist in the door scene? I thought signals were to broadcast to whatever node wants to pick them up? If the custom signal function is needed because it is (it’s the only one that prints), why do we need a custom signal function in the observing node if it doesn’t respond because it’s just using the one from the instanced scene?

maybe first connect, then add_child? please use code formating :slight_smile:

I edited it so it looks better. Still not sure why the connected _on_player_entered function isn’t called.

Basically, _on_player_entered is the receiver code for the emitted signal. It really should respond to the signal that is emitted by door!

I don’t have anything identical I can try this with, but it might be that your function in the tilemap node is missing the description parameter?

1 Like

I think I know what’s going on here. In your method

func _on_player_entered():
print(“this never prints”)

you need to pass in the information from the emitted signal in the parentheses.

The player emits “player_entered.emit(“they’re here”)”

So the script reading the signal (“this never prints”) you need

func _on_player_entered(message):
print(message) 
1 Like

Codeformatting is automatically used starting with three backticks ``` ( or inverted quotes ) in a row and ending with three after the code…

…or selecting the lines and using the </> icon…

print("something")
2 Likes

FalseCognate was right.

Since the door scene receiver function saw the signal, I figured the connect function in the tilemap node would also. But there was a problem with the emitted signal. For this, emit_signal works better then signal_name.emit.

Here’s the door scene that works:

extends Area2D

signal player_entered(position)

func _ready():
	pass

func _on_body_entered(body):
	if body.name == "Player":
		emit_signal("player_entered", position)

And here’s the node code that receives the signal:

    var d = door.instantiate()
	add_child(d)
	d.player_entered.connect(_player_nearby)

func _player_nearby(position):
	print("they're here")
	var location = local_to_map(position)

Thanks everyone

1 Like

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