How do I instance preloaded scenes from an array?

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

Hi all.

I have a little situation. I have an array with a couple preloaded scenes, and want to have them be instanced at random.

Starlane.gd

extends Node2D

var n_ship_freight = preload("res://ships/npcs/neutral/freighter.tscn")
var n_ship_transport = preload("res://ships/npcs/neutral/transport.tscn")
var ship_array = [n_ship_transport, n_ship_freight]
var unknown = randi() % ship_array.size()

func _ready():
	randomize()



func _on_Lane1A_SpawnTimer_timeout():
	var nship_pos = self.get_position()
	var lane_pos = $TrafficArea/Lane1A.get_global_position()
	nship_pos = lane_pos
	$TrafficArea/Lane1A.add_child(unknown.instance())
	$TrafficArea/Lane1A/WaitTimerA.start()


func _on_Lane1B_SpawnTimer_timeout():
	var nship_pos = self.get_position()
	var lane_pos = $TrafficArea/Lane1B.get_global_position()
	nship_pos = lane_pos
	$TrafficArea/Lane1B.add_child(unknown.instance())
	$TrafficArea/Lane1B/WaitTimerB.start()


func _on_Lane2_SpawnTimer_timeout():
	var nship_pos = self.get_position()
	var lane_pos = $TrafficArea/Lane2.get_global_position()
	nship_pos = lane_pos
	$TrafficArea/Lane2.add_child(unknown.instance())
	$TrafficArea/Lane2/SpawnTimer.start()


func _on_Lane3_SpawnTimer_timeout():
	var nship_pos = self.get_position()
	var lane_pos = $TrafficArea/Lane3.get_global_position()
	nship_pos = lane_pos
	$TrafficArea/Lane3.add_child(unknown.instance())
	$TrafficArea/Lane3/SpawnTimer.start()


func _on_WaitTimerA_timeout():
	$TrafficArea/Lane1B/SpawnTimer.start()


func _on_WaitTimerB_timeout():
	$TrafficArea/Lane1A/SpawnTimer.start()

I sort of know what to do, but I don’t exactly know how to do it.

:bust_in_silhouette: Reply From: Magso

add_child(unknown.instance()) won’t work because unknown is an integer. unknown needs to be randomised every time and used as the index of ship_array.

func ...
    #code in function
    unknown = randi() % ship_array.size()
    var new_instance = ship_array[unknown].instance()
    $TrafficArea/Lane1A.add_child(new_instance)

Hey, thanks!

I messed around with it a little, too. Putting ‘unknown’ and ‘new_instance’ up in the global variable section causes an error with parenting, and leaving only ‘unknown’ in the global section causes it to only use one of the different ships in the array.

System_Error | 2019-11-03 21:25

I once did something like this by mistake.

var new_instance
func ...
    new_instance = ship_array[unknown].instance()

Every time a new instance is created it deletes the previous instance because it’s using the same variable rather than creating a new variable in the function. (there’s probably a better way of describing this)

Magso | 2019-11-04 18:24