The easiest way to access newly spawned childs is to save them in a variable after creating them. Practically this is what you are doing (the enemy is in enemy variable), but you lose access to that variable after the for loop.
Here's how'd I do it. I have moved the code for spawning single enemy to a separate function, as it makes the thing a bit easier. Also randomize() initializes the random number generator, but you can consequently call for random numbers after that. No need to initialize it multiple times (as it might create needless overhead).
Code from answer is considered to be at TargetLine.gd. You might need to modify bits of this to work in your project, but I hope that the principles are clear.
# Use one random number generator repeatedly
var rand = RandomNumberGenerator.new()
# Preload resources on startup
var enemyscene = preload("res://EnemyShip.tscn")
var target_line_scene = preload("res://TargetLine.gd")
func _ready() -> void:
rand.randomize() # randomize needs to be called only once, as it initializes the genetaror
func repeat_me():
if G.player_alive == 1:
# Spawn enemy pair
var enemy1 = spawn_enemy()
var enemy2 = spawn_enemy()
# Add line between them
var line = target_line_scene.new()
line.target1 = enemy1
line.target2 = enemy2
add_child(line)
# Spawns a single enemy and returns it
func spawn_enemy():
var screen_size = get_viewport().get_visible_rect().size
var enemy = enemyscene.instance()
var x = rand.randf_range(0, screen_size.x)
var y = rand.randf_range(0, screen_size.y)
enemy.position.y = y
enemy.position.x = x
add_child(enemy)
return enemy