4
\$\begingroup\$

I will change a scene on button click. But not change the main scene with button.

Node structure:

main
- scene (with childs)
- button

button.gd:

func pressed():
    get_node("scene").change_scene("res://second_scene.tscn")

It doesn't works.

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

I would keep track of the current scene in a global variable called current_scene and try something like this:

func change_scene(scene_path):
    call_deferred("change_scene_deferred", scene_path) # waits until an idle period when nodes can be removed safely


func change_scene_deferred(scene_path):
    # remove current scene
    current_scene.free()
    print("FREED CURRENT SCENE")

    # instance new scene
    var s = load(scene_path)
    current_scene = s.instance()
    print("INSTANCED NEW SCENE")

    # add new scene to main node
    get_tree().get_root().get_node("Main").add_child(current_scene)
    print("ADDED SCENE TO Main")
\$\endgroup\$
0
\$\begingroup\$

Search and try.... I think this is a bad solution:

func pressed():
    var main= get_tree().get_root().get_node("main")
    var scene = get_tree().get_root().get_node("main/scene")
    main.remove_child(scene)

    var next_scene_resource = load("res://second_scene.tscn")
    var next_scene = next_scene_resource.instance()
    main.add_child(next_scene)
\$\endgroup\$
1
  • 1
    \$\begingroup\$ I see an attempt to edit this answer with an assessment of the code. GameViewer, if this is you attempting to update your answer, please merge your accounts so you can edit posts under your own ID. If this was another user wanting to share a critique of the code, please use the commenting or voting features, rather than modifying the answer itself, or suggest an edit with a correction to the issue. \$\endgroup\$
    – DMGregory
    Commented Aug 19, 2018 at 11:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .