Scene getting deleted?

Godot Version

4.2.1

Question

When running the following code, instantiated_scene gets deleted after _on_pressed() ends, so _on_aoh_finished only sees it as a null. Why?

extends Button

u/onready var scene = $“…/…/…”.scene

var instantiated_scene = null

func _on_pressed():

instantiated_scene = preload(“res://survivors_game.tscn”).instantiate()

var chosen = get_parent()

var chosen_body = chosen.get_node(“SquareBody”)

print(instantiated_scene)

instantiated_scene.get_node(“Player”).get_node(“Kay1”).get_node(“SquareBody”).texture = chosen_body.texture

print(instantiated_scene)

$“…/…/…/AOH!”.play()

$“…/…/…/Camera2D”.shake(0.2,1)

func _on_aoh_finished():

if instantiated_scene:

print(instantiated_scene)

get_tree().root.add_child(instantiated_scene)

$“…/…/…”.queue_free()

Edit: I just saw that your other function adds it to the tree. Try adding it earlier right after you instantiate it and see if that works.


I believe that is because the instantiated_scene is not attached to your current tree.
You will need to add it a node that exists in your tree.

The simplest method would be to use

instantiated_scene = preload(“res://survivors_game.tscn”).instantiate()
add_child(instantiated_scene)

This will add the instantiated_scene to the current Node with the script running.

Here is the reference from the Godot Documentation

Try this out and let me know if it works. Cheers :beers: