Created
April 12, 2023 12:25
-
-
Save brettchalupa/1c68e37d2788a3d36f74222c354baac2 to your computer and use it in GitHub Desktop.
Scene Switching in Godot 4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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