In our last tutorial, we learned how to create a button in Godot. In this tutorial, we will use that button to destroy the node in our scene during runtime.
Godot has a little weird terminology for destroying a node. They call it free.
You can just call “Free(node)” in your function to destroy the node. Change the button code to the one below
func _on_Button_pressed(): free()
This code might lead to game crashes.
The reason being, this code immediately frees/destroys the node. If the node was active in the game scene, then the game crashes.
To avoid this, we can make a simple change to the code
func _on_Button_pressed(): queue_free()
“queue_free()” queues the object to be destroyed in the next frame rather than destroying it immediately. This makes sure the object is not active in the current frame and does not crash the game.
One more thing to check is if the node is already freed. Here is the code to check that. This is only required if you are deleting a different node from the one your script is attached to.
extends Spatial var object_to_delete func _ready(): object_to_delete=get_node("../glass cube2") func _on_Button_pressed(): if is_instance_valid(object_to_delete): object_to_delete.queue_free()
Thats it for this tutorial. If you have any questions leave it in the comment below.