Skip to content

Instantly share code, notes, and snippets.

@brettchalupa
Created April 12, 2023 12:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brettchalupa/1c68e37d2788a3d36f74222c354baac2 to your computer and use it in GitHub Desktop.
Save brettchalupa/1c68e37d2788a3d36f74222c354baac2 to your computer and use it in GitHub Desktop.
Scene Switching in Godot 4
# How to switch to a PackedScene
extends Node2D
@export var level_2_scene:PackedScene
func _on_level_2_button_pressed() -> void:
get_tree().change_scene_to_packed(level_2_scene)
# How to switch to a File resource path
extends Node2D
func _on_level_1_button_pressed() -> void:
get_tree().change_scene_to_file("res://level_1.tscn")
# PREFERRED APPROACH
# Set up the Autoload singleton as a global variable and then use this like:
# SceneSwitcher.switch_scene("res://level_1.tscn")
extends Node
var current_scene = null
func _ready() -> void:
var root = get_tree().root
current_scene = root.get_child(root.get_child_count() - 1)
func switch_scene(res_path):
call_deferred("_deferred_switch_scene", res_path)
func _deferred_switch_scene(res_path):
current_scene.free()
var s = load(res_path)
current_scene = s.instantiate()
get_tree().root.add_child(current_scene)
get_tree().current_scene = current_scene
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment