How to instance and iterate over in one method?

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

I’m trying to create a method that I call between my splash and main menu to instantiate and record all spawn positions from my levels. I’m getting an !is_inside_tree() error, likely since I’m trying to iterate over children directly after adding the node to my tree.

func get_spawn_position_from_stage():
	for path in stage_paths:
		# instance level to get spawnpoint
		var stage_path = path
		var temp_level = preloaded_level_dict[stage_path].instance()
		var canvas_layer = CanvasLayer.new()
		canvas_layer.layer = -9999
		canvas_layer.add_child(temp_level)
		var point
		for child in temp_level.get_children():
			if child.name == "SpawnPoint":
				point = child.global_position
		canvas_layer.queue_free()
		print(point)

Any way around this? In short, I want to instantiate, iterate over, then free super quickly.

I tried embedding the iteration over children into a separate method that I use a call_deferred() to call, but no luck.

Is there a reason why you need to add them to the tree? Do spawn points appear only in _ready or something? Because otherwise you could simply do a tree traversal and even save some time (a bunch of extra logic runs when a node enters the tree).

Otherwise, would be interesting to know which line causes the error.

Zylann | 2020-04-07 09:42