How to get scene after calling get_tree().change_scene_to_file()?

Godot Version

4.2.1

Question

I’m having an issue where I want to have Godot switch my game scene to a new scene and then set a few parameters on the new scene to affect where some objects are in the scene. Unfortunately, immediately after calling get_tree().change_scene_to_file(), the tree’s current_scene is null. I also tried waiting for the next process_frame event, but that’s not enough to ensure the scene has been added to the tree. There also doesn’t seem to be any signal to indicate that the new scene has been loaded and is ready to go. And you are not allowed to simply set current_scene to a node.

How can I get the scene as soon as possible after it is loaded so I can make some changes to it?

I think you can pull the scene into the script to get a reference to it.

I’m sure there are better ways but my stage end script looks like this:

extends CollisionShape2D

@onready var collision_shape_2d = $“.”
const LEVEL_2 = preload(“res://level2.tscn”)
@onready var timer = $“…/Timer”

func _on_stage_end_body_entered(body):
Engine.time_scale = 0.2
timer.start()

func _on_timer_timeout():
Engine.time_scale = 1
get_tree().change_scene_to_file(“res://level2.tscn”)

The timer is not necesary but i felt like it was so abrupt to switch already on the next frame. Felt more natural with a tiny moment of slowdown first.

I don’t think using a timer is a good idea. You have no guarantee that the scene will be loaded after that many seconds. You may also be needlessly waiting too long. You can also have different wait times on different machines running the code. It would be better to have some way to know precisely after the scene changes.

If you have no problem blocking the main thread, then use load to retrieve a PackedScene blocking the main thread and then after use change_scene_to_packed. Wait a single frame and then you should be able to access the current_scene.

Reference: SceneTree — Godot Engine (stable) documentation in English

Its just a tiny pixel game so it will load! The timer is for how long the engine time scale will be slowed down, as you pass the goal line.

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