PathFollow2D doesn't show instances added through code

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

Hello,

i try to add enemies trough Spawner script (it works if i add enemies without a Path2D). but if i add enemies and PathFollow2D by code, they don’t appear in the game, but the Slime appears in the Remote and it’s moving (with it’s own script, not by PathFollow2D).
PathFollow2D and Slime are scenes instanced through code. If i add PathFollow2D and Slime through editor, it works and the Slime appears in the game, but it doesn’t if it’s done by code.
any ideas why is this happening?

enter image description here

var Enemy = preload("res://enemy/slime/Slime.tscn")
var path = preload("res://path/PathFollow2D.tscn")

func _on_Timer_timeout():
if enemies_to_spawn:
	randomize()
	var enemy = Enemy.instance()
	connect_to_enemy_signals(enemy)
	var pathInstance = path.instance()		
	enemy.position = Vector2(rand_range(1051,1096),rand_range(107,233))
	var scene_root = get_parent().get_node("Path2D")
	pathInstance.add_child(enemy)		
	scene_root.add_child(pathInstance)
	enemies_to_spawn -= 1
:bust_in_silhouette: Reply From: jfran

i didn’t write where the PathFollow2D should spawn, so they spawned outside the window and i thought it was a bug, but was my mistake.
instead of telling the enemy where to spawn, i had to tell the PathFollow2D where to spawn, cus the enemy is a child_node and it doesn’t matter if a tell to spawn in x= 10 and y=50, he will always spawn where PathFollow2D spawns.

instead of:

enemy.position = Vector2(rand_range(1051,1096),rand_range(107,233))

should be:

pathInstance.position = Vector2(rand_range(1051,1096),rand_range(107,233))