Cambiar escenas manualmente

Sometimes it helps to have more control over how you swap scenes around. A Viewport's child nodes will render to the image it generates. This holds true even for nodes outside of the "current" scene. Autoloads fall into this category, and also scenes which you instantiate and add to the tree at runtime:

var simultaneous_scene = preload("res://levels/level2.tscn").instantiate()

func _add_a_scene_manually():
    # This is like autoloading the scene, only
    # it happens after already loading the main scene.
    get_tree().root.add_child(simultaneous_scene)

To complete the cycle and swap out the new scene with the old one, you have a choice to make. Many strategies exist for removing a scene from view of the Viewport. The tradeoffs involve balancing operation speed and memory consumption, as well as balancing data access and integrity.

  1. Delete the existing scene. SceneTree.change_scene_to_file() and SceneTree.change_scene_to_packed() will delete the current scene immediately. You can also delete the main scene. Assuming the root node's name is "Main", you could do get_node("/root/Main").free() to delete the whole scene.

    • Descargas de la memoria.

      • Pro: La RAM ya no arrastra el peso muerto.

      • Con: Volver a esa escena ahora es más costoso, ya que debe cargarse nuevamente en la memoria (toma tiempo y memoria). No es un problema si no es necesario volver pronto a esa escena.

      • Con: Ya no tienes acceso a los datos de esa escena. No es un problema si no necesitas usar esos datos pronto.

      • Nota: Puedes ser útil preservar los datos en una escena que pronto será eliminada, volviendo a adjuntar uno o varios de sus nodos a una escena diferente, o incluso directamente al SceneTree.

    • Detención de procesamiento.

      • Pro: No nodes means no processing, physics processing, or input handling. The CPU is available to work on the new scene's contents.

      • Con: El procesamiento y el manejo de entrada de esos nodos ya no operan. No es un problema si no es necesario utilizar los datos actualizados.

  2. Hide the existing scene. By changing the visibility or collision detection of the nodes, you can hide the entire node sub-tree from the player's perspective.

    • La memoria aun existe.

      • Pro: You can still access the data if needed.

      • Pro: Ya no es necesario mover más nodos para guardar datos.

      • Con: More data is being kept in memory, which will be become a problem on memory-sensitive platforms like web or mobile.

    • Continuación de procesamiento.

      • Pro: Data continues to receive processing updates, so the scene will keep any data within it that relies on delta time or frame data updated.

      • Pro: Los nodos siguen siendo miembros de grupos (ya que los grupos pertenecen al SceneTree).

      • Con: The CPU's attention is now divided between both scenes. Too much load could result in low frame rates. You should be sure to test performance as you go to ensure the target platform can support the load from this approach.

  3. Remove the existing scene from the tree. Assign a variable to the existing scene's root node. Then use Node.remove_child(Node) to detach the entire scene from the tree.

    • Memory still exists (similar pros/cons as hiding it from view).

    • Processing stops (similar pros/cons as deleting it completely).

    • Pro: This variation of "hiding" it is much easier to show/hide. Rather than potentially keeping track of multiple changes to the scene, you only need to call the add/remove_child methods. This is similar to disabling game objects in other engines.

    • Con: A diferencia de ocultarla solo de la vista, los datos contenidos dentro de la escena se volverán obsoletos si dependen del tiempo delta, la entrada, los grupos u otros datos que se derivan del acceso a SceneTree.

There are also cases where you may wish to have many scenes present at the same time, such as adding your own singleton at runtime, or preserving a scene's data between scene changes (adding the scene to the root node).

get_tree().root.add_child(scene)

Otro caso podría ser mostrar varias escenas simultáneamente usando SubViewportContainers. Esto es óptimo para renderizar contenido diferente en distintas partes de la pantalla (por ejemplo, minimapas, multijugador en pantalla dividida).

Each option will have cases where it is best appropriate, so you must examine the effects of each approach, and determine what path best fits your unique situation.