Signals don't work

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

hello! I’m trying to make my character appear in the left of the room when it’s coming from outside, and in the right of the room when it’s coming from another room. I can travel between scenes(outside-room1,room1-room2 and viceversa) with Area2Ds. I only have one script for all the Area2Ds, so when i travel from room1 to room2 the code looks like this:

if get_tree().get_current_scene().get_name() == "home-floor1-livingroom":
		if right==true:
			get_tree().change_scene("res://scenes/home-floor1-kitchen.tscn")
			print("yes1")
			emit_signal("left")

here the yes is printed…I want to set the character’s position in code, but it doesn’t work. The character remains where I put it with my mouse,the code doesn’t change anything. The receiving code look like this:

func _ready():
	print("yes2")
	var teleportation=get_node("Area2Dkitchen1")
	teleportation.connect("left",self,"teleport_left")

func _on_Area2Dkitchen1_left():
	print("yes")
	$Player.position.x=100
	
func teleport_left():
	print("yes")
	$Player.position.x=100

I tried to connect it manually(_on_Area2Dkitchen1_left()) and from the code(teleport_left()), it doesn’t even print “yes”. What am I doing wrong? the area2d and the room is in the same scene and i connected them correctly. Any advice? I am still a begginer, so any help is useful and well received.

The character remains where I put it with my mouse

You mean, in the editor?

When you do change_scene(), the current scene and all its children get removed from the scene tree, and the next one is added in its place. That means if the receiving node is child of the previous scene, it will be wiped out anyways so changing position will be irrelevant.
change_scene actually runs with call_deferred internally so it’s not immediate, even if you do $Player.position.x = 100 afterwards. Maybe waiting one frame could do.

You should either make your player independent from scene switching (so each room would have NO player instance in it), or, if you instanced the player in every room, get that other instance after it has been switched.

Also, make sure the code doing modifications to $Player does not get wiped out itself by the scene change. If it is inside in the previous scene, it will be deleted so it might cause errors if you try running code afterwards in time (because tree access would no longer work since self would not be in the tree anymore).

And of course, check the logs in the console. Sometimes get_node (aka $) fails but it doesn’t stop the game from running.

Zylann | 2019-09-17 20:59

Thank you for your advice! It worked!

Sakura37 | 2019-09-18 17:28