Help with Galaga Remake

Godot Version

Godot 4

Question

I’m trying to make a galaga remake in Godot, but my code for having the enemies randomly spawn is not working. I have an enemy spawner scene with a node called SpawnPositions. The children of that node are four Marker2Ds that I have placed where I want the enemies to spawn. When I run the code, the enemies are only spawning on the bottom of the screen, not at all four locations. I have the code I am using below. Help is appreciated, thanks!

If you share code, please wrap it inside three backticks or replace the code in the next block:

extends Node2D

@export var enemy_scene: PackedScene = preload("res://images/enemy.tscn")

var spawn_positions: Array[Node] = []

func _ready():
	randomize()
	spawn_positions = $SpawnPositions.get_children()
	$SpawnTimer.start()

func spawn_enemy():
	if spawn_positions.is_empty():
		print("No spawn positions")
		return

	var index = randi_range(0, spawn_positions.size() - 1)
	var enemy = enemy_scene.instantiate()
	enemy.global_position = spawn_positions[index].global_position
	add_child(enemy)

func _on_spawn_timer_timeout():
	spawn_enemy()

You can’t set the global position of the enemy before it’s added to the scene tree, it doesn’t have a concept of a global position yet.

The enemy is in a different scene.

Swap these two lines

	enemy.global_position = spawn_positions[index].global_position
	add_child(enemy)

It’s doing the same thing still.

What does the node tree of the enemy scene look like?

Area2D with a Sprite2D and a CollisionPolygon2D as the children.

This code could return the same index repeatedly:
var index = randi_range(0, spawn_positions.size() - 1)

You have to check that it is actually getting a range of indexes.
Once again I recommend using seed(n) where n is a known value until you have working code.
seed(n) will ensure that calls to randi() will return the same set of random numbers. This is very helpful for debugging.

func _ready():
	#randomize()
    seed(0)