can't remove child instance

Godot Version

4.7

Question

Hello! I am struggling to remove a child from my scene. As you can see in func definememory() I create a child, but neither queue_free() nor remove_child() works to remove it. (I added prints to check if the rest of the code runs and they return prints as intended.

Basically what I need to do is to be able to create an instance and then after a certain amount of time I want it to disappear (ideally use queue_free to unload it qnd not take up space).

I provided the entire script (yea its pretty simple, if you know ways to optimize lmk!), but if there’s additional info that is needed just tell me-

extends Node2D
@onready var memory: PackedScene = preload("res://scenes/memory.tscn")
@onready var button: Button = $Button
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var anim_timer: Timer = $Timer
var remove_memory := false

func _define_memory():
	var memory_bubble = memory.instantiate()
	memory_bubble.position = Vector2(1000,-1000)
	memory_bubble.scale = Vector2(3,3)
	if remove_memory:
		print("hi")
		memory_bubble.queue_free()
	else:
		add_child(memory_bubble)
		print("nu")

func _on_button_pressed() -> void:
	anim_timer.start()
	_define_memory()
	animation_player.stop()
	remove_child(button)
	remove_memory = true


func _on_timer_timeout() -> void:
	_define_memory()

You’re changing the value of memory_bubble variable on each run of _define_memory() function, because it’s a function scope variable, not class scope.
Then every time you run the _define_memory(), you create a new instance of memory_bubble, and you never can delete the old one, because you don’t have any reference to it anymore.

Something like this should work, assumming all the rest of the logic in your code works.

extends Node2D
@onready var memory: PackedScene = preload("res://scenes/memory.tscn")
@onready var button: Button = $Button
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var anim_timer: Timer = $Timer
var remove_memory := false
var memory_bubble

func _define_memory():
	if remove_memory:
		print("hi")
		memory_bubble.queue_free()
		return
	memory_bubble = memory.instantiate()
	memory_bubble.position = Vector2(1000,-1000)
	memory_bubble.scale = Vector2(3,3)
	add_child(memory_bubble)
	print("nu")

func _on_button_pressed() -> void:
	anim_timer.start()
	_define_memory()
	animation_player.stop()
	remove_child(button)
	remove_memory = true


func _on_timer_timeout() -> void:
	_define_memory()