0 votes

Hey folks,

I want to switch between two scenes based on their paths. At the moment I have a global that handles the switching, as so:

extends Node

var current_scene_path = null
var scenes = {}

func _ready():
    # Fetch the current scene and add it to the scenes dictionary
    var current_scene = get_tree().get_current_scene()
    current_scene_path = current_scene.get_path()
    scenes[current_scene_path] = current_scene

func change_scene(path):
    call_deferred("_change_scene", path)

func _change_scene(path):
    if current_scene_path == path:
        # Can't switch to the scene we are currently in
        return

    if not path in scenes:
        # If path is not scenes then load the scene from disk and then switch to it
        var s = ResourceLoader.load(path)
        var scene = s.instance()
        scenes[path] = scene
        return _change_scene(path)

    # Remove the current scene from the scene tree
    get_tree().get_root().remove_child(scenes[current_scene_path])

    # Load the already loaded scene from the scenes dictionary
    var scene = scenes[path]
    current_scene_path = path
    get_tree().get_root().add_child(scene)
    get_tree().set_current_scene(scene)
    return

However the problem lies in the ready function. It tries to fetch the path of the current scene, which ends up being /root/game and not res//whatever which is what change_scene is expecting, thus if change scene is called with the original starting scene it will load a new scene instead of using the existing one.

Please can you suggest how to get the resource path of the current scene or another workaround to my problem, thank you!

in Engine by (12 points)

1 Answer

+2 votes

Here is what document in editor says.

* NodePath get_path() const

Return the absolute path of the current node. This only works if the current node is inside the scene tree (see is_inside_tree()).


* String get_filename() const

Return a filename that may be contained by the node. When a scene is instanced from a file, it topmost node contains the filename from where it was loaded (see set_filename()).

Based on this information, you should use get_filename() instead of get_path() in your case.

by (9,796 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 Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.