Code errors causing crashes

Godot Version

4.4.1

Question

`I’m trying to code a function in my 2D platformer where the player collides with a “button” that removes part of the roof for the player to continue forward. Yet, when I tried to code that function with the collision 2D nodes, it crashes the game before it can even begin. What have I done wrong for this to happen?

This is code I have used for the function:
extends Node2D
@onready var button=$“.”

#Called when the node enters the scene tree for the first time.
func _ready() → void:
pass # Replace with function body.

Called every frame. ‘delta’ is the elapsed time since the previous frame.

func _process(delta: float) → void:
pass

func _on_area_2d_body_entered(body: Node2D) → void:
pass # Replace with function body.
button.get_tree().quit()

So, can anyone tell me what’s wrong. If you need to, I can try and send a copy of the game so you can try it yourself because I’m new to Godot and are just going off of what research and data I can find to code this game`

This quits the entire game.

Maybe you mean to use queue_free() to delete this one object the script is attached to?

I’ll try that

This is creating a variable button that points to the current node
$“.” this is shorthand for get_node(current node)
There isn’t a need to do that.
The script is attached to the current node and you have direct access to all the nodes properties and methods.

#@onready var button=$“.” # unnecessary
func _on_area_2d_body_entered(body: Node2D) → void:
   #button.get_tree().quit() # unnecessary 
   #get_tree().quit() # works exactly the same as above   
   queue_free() # as gertkeno says, sets this current node to be freed

Okay, so while the game doesn’t crash anymore, the collision is gone before I even reach the button area. I know I’m not accidentally colliding with it either as I’ve set it in a specific location to where it wouldn’t collide. What’s wrong now?

Keep in mind that the body_entered signal is if any body enters, including static bodies or from tile maps. Maybe you should use an if statement to filter only the player, you could do this by the body’s name for example

if body.name == "Player":
    queue_free()
2 Likes

That worked, thank you so much!

I was stressing out over this for so long, but now I have to figure out a new mechanic, so expect me to be here in the forums again

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.