Await causing get_tree() to return null

Godot Version

I’m relatively new at Godot. However, there’s an issue that I can’t seem to get around that’s bugging me. One of these lines of code causes an error, while the other one is fine.

func _change_scenes(camera, event, position, normal, shape_idx, path):
	
	if not event is InputEventMouseButton: return
	
	fd.play('fade_out')
	
	await fd.animation_finished

	get_tree().change_scene_to_file(path)
	
	  
	return

This causes an error, as get_tree() returns null, and therefore cannot call the function. However,

func _change_scenes(camera, event, position, normal, shape_idx, path):
	
	if not event is InputEventMouseButton: return
	
	fd.play('fade_out')

	get_tree().change_scene_to_file(path)
	
	  
	return

Runs just fine. Can I please have some help debugging here? I’m fine to give more details.

The issue is that you are receiving 2 InputEventMouseButtons events. One when a button is pressed and one when it’s released. Both events will await to the end of the animation. The first time is okay and the scene will change but the second one will fail as the scene has changed and the node can’t access the SceneTree anymore.

  • Button pressed
    • Play Animation
    • Wait (1)
  • Button released
    • Play animation (it was already playing so it won’t do anything)
    • Wait (2)

  • Animation finishes
  • Change scene (1)
    • Scene is changed
    • The node exits the tree
  • Change scene (2)
    • The node is not in the tree
    • get_tree() fails

This is extremely helpful. Thank you for explaining.

Here’s my updated code, for any forum lurkers who run into this same issue – though I’m sure you can do it more optimized than me!

func _change_scenes(camera, event, position, normal, shape_idx, path):
	
	if not event is InputEventMouseButton: return
	if not event.pressed: return
	
	fd.play('fade_out')
	
	await fd.animation_finished

	get_tree().change_scene_to_file(path)
	
	return

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