Game crashing without error when changing scene

Godot Version

4.1

Question

I’m using this script to change scenes when the player has entered an area:

extends Node2D

@onready var scene = load("res://scenes/" + get_meta("scene_name") + ".tscn")

func _on_area_2d_area_entered(area):
  if area.get_parent().name == "Player":
    $Area2D.set_deferred("monitoring", false)
    get_tree().create_tween().tween_property($Area2D/Sprite2D, "modulate", Color(1,1,1,1), 0.1) # fade to black

    await get_tree().create_timer(0.1).timeout
    get_tree().call_deferred("change_scene_to_packed", scene)

Sometimes (about once every 20 tries) when the scene changes the game will freeze for half a second then close without showing any error. I tried using get_tree().unload_current_scene()and a few other methods but nothing fixed it.

I’m pretty sure there’s nothing else in the scenes that could cause this. Also happens on other devices.

A node with name Player may be entering the area twice or more times and the await is triggering the change of the scene twice or more times. The first time it works because the node has access to the scene tree but the second time it fails because the node is not in the scene tree anymore and crashes.

1 Like

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