Multiple instances of custom script losing signal connectivity

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

I’m creating a custom plugin for my game, and I created a script that extends Spatial so I can add it to the scene tree.

What this script is supposed to do is create two Area nodes with accompanying CollisionShapes and SphereShapes (the first larger than the second). I then add the Area nodes as children of the script itself and connect the first Area’s area_entered(area) and area_exited(area) signals through code. The script is supposed to be instantiated multiple times, each one looking out for the others. The first Area looks for the second, smaller Area of the other instances; I use signals to figure out who is seen or not.

However, when I create multiple instances of the script and add to the scene tree, only the last to be created will have its Area’s signals work.

Here is the _init function of the script:

func _init(_object : Spatial = null) -> void:
	name = "RegionObject"

	add_to_group("RegionObjects", true)

	object = _object

	detector_area.name = "DetectorArea"
	detector_area_col_shape.shape = detector_shape
	detector_area_col_shape.name = "DetectorShape"
	detector_shape.radius = detector_shape_radius
	detector_area.add_child(detector_area_col_shape)

	add_child(detector_area)

	print("Connecting RegionObject signals")
	detector_area.connect("area_entered",
							self,
							"_on_detector_area_entered")
detector_area.connect("area_exited",
							self,
							"_on_detector_area_exited")

	detection_area.name = "DetectionArea"
	detection_area_col_shape.shape = detection_shape
	detection_area_col_shape.name = "DetectionShape"
	detection_shape.radius = detection_shape_radius
	detection_area.add_child(detection_area_col_shape)

	add_child(detection_area)
:bust_in_silhouette: Reply From: Bean_of_all_Beans

Okay, I figured out my problem. Unlike what I had thought, the problem was not with my _init function, but with the actual function called by the signal (_on_detector_area_entered, in this case).

In the function, I had the the if statement if not (area.get_parent() == self) and area.get_parent().name == "RegionObject" and not area.name == "DetectorArea":. Because Godot automatically modifies the name of objects added to the scene tree if the name is already taken (I had two-plus RegionObjects added to my scene tree, The first RegionObject was named just that. The second would have a name like @RegionObject@4 or whatnot (I do not fully understand where those numbers come from; point is they are added onto the name).

Anyone who comes across this wondering why signals across duplicates of a scene or custom node, make sure you are not checking against the a node/PackedScene with a specific name, especially if the node/PackedScene is added multiple times to the scene tree through code.