Replacing one node with another in MultiplayerSpawner

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

I’m trying to follow this tutorial on changing scenes in a multiplayer game. I have the following structure:

- world (Node3D)
  - level (Node3D)
    - actual_scene (custom)
- MultiplayerSpawner

The level has the following function:

func change_level(scene: PackedScene):
    assert(get_child_count() == 1)
    var current = get_child(0)

When I call it only on the server, the server correctly removes the previous level and adds the new one, but the client only receives the new level from the multiplayer spawner but doesn’t remove the previous one, ending up with having both.

I tried to change the MultiplayerSpawner to use custom spawns by adding this code to the world:

func _ready():
    $MultiplayerSpawner.spawn_function = $level.change_level

func change_scene(scene: PackedScene):

but then I got instantiate_custom: Failed to call spawn function. and on_spawn_receive: Condition "!node" is true. Returning: ERR_UNAUTHORIZED.

Any idea what I’m doing wrong and how do I remove the previous node while adding a new one?

:bust_in_silhouette: Reply From: codabase

I would keep all logic related to changing levels only inside your Singleton. So instead of a change_level function being in the level, just use the Singleton.

You could adjust the “change_scene()” function to first:
• Instantiate the new scene, but don’t add it to scene tree yet
• Move any needed nodes to the new scene tree (if needed)
• Remove the old scene

I imagine that the change level function is removing the first scene, and then a node cannot be found on the spawn function since the node is gone.

Let me know if I need to clarify anything. I think if you allocate your functions logic to be handled at the singleton level it should make it more organized and clear

Thanks for the suggestion for using a singleton, that sounds like a good idea but won’t necessarily solve the problem that I have.

I don’t think “change level function is removing the first scene, and then a node cannot be found on the spawn function” is accurate: if this was the case, then I’d get an assertion error in the first line of the change_level.

sygi | 2023-03-27 18:37