YSort problem on a randomly generated map with random spawns

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

So i have 2 kinematic bodies under Ysort each containing different sprites (One player sprite and one enemy sprite.
Also the map is randomly generated world and also the player and enemy positions are mapped to world randomly.
So here’s how the player spawn code looks like

onready var Player = get_node("YSort/Player")

func _ready() -> void:
    Player.position = map.player_spawn(arr[arr_length-1])

Here arr is the array of available Vector2 positions for spawning and arr_length is len(arr)
This works perfectly fine.

But for enemy spawns i decided to use preload the Kinamticbody2d node directly from the location of its .tscn file. Which looks like this

onready var enemy_grunt = preload("res://enemies/EnemyGrunt.tscn")

By doing this i was able to spawn the desired amount of EnemyGrunt kinamatiic bodies into a Node2D container called enemy_container. It looks like this

onready var enemy_container = get_node("YSort/enemy_container")
onready var enemy_grunt = preload("res://enemies/EnemyGrunt.tscn")

func spawn_enemy(num):
	for i in range(num):
		var enemy = enemy_grunt.instance()
		var random_key = get_random_key()
		var spawn_value = random_key
		enemy.position = map.enemy_spawn(spawn_value)

When i Place the enemy_container node and EnemyGrunt node under Ysort it wont work as the function is spawning enemy sprites directly from the preloaded EnemyGrunt.tscn.

And if i want Ysort to work i need to modify a code a little bit like this

onready var Enemy_Grunts = get_node("YSort/EnemyGrunt")
func spawn_enemy(num):
	for i in range(num):
		enemy_container.add_child(Enemy_Grunts )
		var random_key = get_random_key()
		var spawn_value = random_key
		Enemy_Grunts .position = map.enemy_spawn(spawn_value)

SO i hade to remove the line var enemy = enemy_grunt.instance() as it does not work with var Enemy_Grunts = get_node(“YSort/EnemyGrunt”).

Without out instancing i’m not able to spawn the desired number of enemies using using num variable. If i want to add more i need to duplicate the EnemyGrunt node inside ysort. This is very counter productive.

So is there anyway i can add Ysort to sprites manually or make a instance of Enemy_Grunts under YSort ?

Scene Tab
The game looks without YSort

:bust_in_silhouette: Reply From: 2Dfanatic

Instead of adding enemy to the enemy container directly add child to YSort.
Change this to