Why is get_current_scene() seeming to return the node but not the attached script? Godot 4

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By SneakySteve

I have this code:

await get_tree().get_current_scene().name == "Lobby"

My Lobby.tscn looks like this:

and the script attached to the Lobby (root) node is:

extends Node

func add_player_to_lobby(id):
    print("Adding " + str(id) + " to the lobby")

The error says:
"Invalid call. Nonexistent function ‘add_player_to_lobby’ in base ‘Control ()’.

And I’m not sure what is going on. It seems to me that I am in fact changing to the lobby scene otherwise the await would not pass, as the error is triggered by the “add_player_to_lobby” line of code. But somehow I’m not able to fetch the script, only the node? If it helps, the lobby script is a normal script and the one I mention above is a singleton (autoload and global variable)

:bust_in_silhouette: Reply From: LeslieS

Put a print statement prior to the error line to see what scene you are actually getting:

await get_tree().get_current_scene().name == "Lobby"

Is Lobby a Control node?

Okay, I put in a print statement and that says that its actually still in my MainMenu scene. But if I click the remote tab I can see it successfully switched to Lobby? Is await just not waiting long enough maybe? If so, how can I make it actually wait for the scene change to finish?

SneakySteve | 2022-12-17 20:24

The call to change scenes is deferred as you already knew.
The new await keyword works with signals and won’t work the way it is set up here.
await in the docs (found here):

Changing scenes is a tradeoff process and you should read this.
Using one of the methods in that link:
Preload the scene

var lobby_scene = preload("res://scenes/core/Lobby.tscn")

var lobby = lobby_scene.instantiate()

LeslieS | 2022-12-17 21:37

Thank you, preloading solved it.

SneakySteve | 2022-12-17 22:08