Generating a scene at runtime

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By mydoghasworms
:warning: Old Version Published before Godot 3 was released.

I am trying to generate a scene at runtime following instructions from here: https://forum.godotengine.org/903/how-to-save-a-scene-at-run-time

This is my code:

extends Node2D

func _ready():
	generate_level()
	
func generate_level():
	var root = Node2D.new()
	root.set_name("level")
	var boundary = Node2D.new()
	boundary.set_name("boundary")
	root.add_child(boundary)
	boundary.set_owner(root)
# Create a boundary
	var sprite
	for i in range(3):
		sprite = Sprite.new()
		sprite.set_name(str("sprite", i))
		boundary.add_child(sprite)
		sprite.set_owner(boundary)
	var packed_scene = PackedScene.new()
	packed_scene.pack(root)
	ResourceSaver.save("res://my_scene.tscn", packed_scene)

However, when I open “my_scene.tscn”, it only has the root node and its child called “boundary”. The sprites I added to the boundary are not present.

Why doesn’t this work?

:bust_in_silhouette: Reply From: mydoghasworms

Ah, I got the answer after looking at one of the GitHub projects pointed to in the Reddit discussion referred to in the above Q&A:

All descendants, it seems, must have set_owner called with the root of the scene, like so:

sprites[i].set_owner(root)

and not of their immediate parent.