0 votes

I am trying to generate a scene at runtime following instructions from here: https://godotengine.org/qa/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?

in Engine by (117 points)

1 Answer

0 votes
Best answer

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.

by (117 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.