+11 votes

like the title says how do i do it i have seen other code for changing scene and it is a bit different from the others
i want to know what is the base code of scene changing

asked Feb 28, 2018 in Engine by Newby (378 points)

2 Answers

+12 votes

The simplest is this:


Under the hood, changing scene is as simple as replacing a node in the tree by another:

# Remove the current level
var level = root.get_node("Level")

# Add the next level
var next_level_resource = load("res://path/to/scene.tscn)
var next_level = next_level_resource.instance()

root can be any node you want. In the first simplest example, root is the root of the whole scene tree. Once you understand how this works, you can apply this anywhere, and you'll realize "changing scene" is a relative concept. You could change everything if you do it on the root, but you can do that to a part of the tree, so that not everything has to change.

pgregory suggested background loading but it's not required to change scene. You might need it only if your scene is too big to the point of needing a loading screen.

answered Feb 28, 2018 by Zylann (25,829 points)
edited Nov 27, 2019 by Zylann

If you want it to be compatible with SceneTree.change_scene you may need to set SceneTree.set_current_scene as well. See also Custom scene switcher.

Thanks back to building

You have little misspell in you code

var next_level_resource = load("res://path/to/scene.tscn)
var next_level = next_leve_resource.instance() <------
+2 votes
answered Jun 6, 2019 by spiritabsolute (18 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.