Exiting Back to a Main Scene

Godot 4.4

I am trying to create an exit to a scene by pressing the ESC key, but nothing happens. The scene can be entered by clicking the object.

Here is the code I am using:

func _input_event(viewport, event, shape_idx):
	if event.is_action_pressed("click"):
		print("Inspecting The Lines")
		get_tree().change_scene_to_file("res://scenes/lines_inspection.tscn")
	if event.is_action_pressed("exit"):
		print("Return to Room")
		get_tree().change_scene_to_file("res://scenes/Main.tscn")

The first “if” statement works, but the second doesn’t. The print function does not get called in the second “if” statement.

You should write click section in Main.tscn script and exit section in lines_inspection.tscn, or you can have an autoload to keep both in that script, because if you attach this script to main scene, when you change scene to lines inspection, this script will no longer be in scene tree.

I moved the “exit” statement to the Lines_Inspection scene, but I am still having the same issue.

extends Control

func _input_event(viewport, event, shape_idx):
	if event.is_action_pressed("exit"):
		print("Return to Room")
		get_tree().change_scene_to_file("res://scenes/Main.tscn")

The script was originally attached to a sprite scene, not the main scene. Maybe this could be related to the issue?

I was able to make something that worked by using a button instead of the escape key within the Lines_Inspection scene:

func _on_button_pressed() -> void:
	print("Return to Room")
	get_tree().change_scene_to_file("res://scenes/Main.tscn")

the override _input_event is for interacting with collision objects like areas or rigidbodies, it can detect clicks on the object but keyboard presses are not location-specific. You could override _unhandled_input instead for “exit”

Godot tends to get pretty grumpy when you override functions the engine calls. Obviously there’s different behaviors for different functions/contexts, but as a general rule of thumb “don’t override something you didn’t write in a parent class” has served me pretty well.

I sympathize with the want to make everything as neat as possible by overriding an event like that, but it doesn’t tend to work.

In this case, the Input class can provide a lot of what you’re looking for (i.e. Input.is_action_just_pressed() in _process()). Though that does come with the downside of needing to be careful about whether you have situations where 2 nodes are waiting for the same input, which might lead to unexpected behavior as both functions fire.

Functions in native classes that start with _ are virtual, they are all meant to be overridden/implemented by the user.