SceneTree
Maneja el bucle del juego a través de una jerarquía de nodos.
Descripción
As one of the most important classes, the SceneTree manages the hierarchy of nodes in a scene, as well as scenes themselves. Nodes can be added, fetched and removed. The whole scene tree (and thus the current scene) can be paused. Scenes can be loaded, switched and reloaded.
You can also use the SceneTree to organize your nodes into groups: every node can be added to as many groups as you want to create, e.g. an "enemy" group. You can then iterate these groups or even call methods and set properties on all the nodes belonging to any given group.
SceneTree is the default MainLoop implementation used by the engine, and is thus in charge of the game loop.
Tutoriales
Propiedades
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
Métodos
Señales
Emitida cuando el node entra en este árbol.
node_configuration_warning_changed(node: Node) 🔗
Emitida al llamar a Node.update_configuration_warnings() de node. Solo se emite en el editor.
Emitida cuando el node sale de este árbol.
Emitida cuando el Node.name de node es cambiado.
physics_frame() 🔗
Emitted immediately before Node._physics_process() is called on every node in this tree.
process_frame() 🔗
Emitted immediately before Node._process() is called on every node in this tree.
scene_changed() 🔗
Emitida después de que la nueva escena se añade al árbol de escenas y se inicializa. Se puede usar para acceder de forma fiable a current_scene al cambiar de escena.
# Este código debería estar dentro de un autoload.
get_tree().change_scene_to_file(other_scene_path)
await get_tree().scene_changed
print(get_tree().current_scene) # Imprime la nueva escena.
tree_changed() 🔗
Emitida cada vez que cambia la jerarquía del árbol (los nodos se mueven, se renombran, etc.).
tree_process_mode_changed() 🔗
Emitida cuando cambia el Node.process_mode de cualquier nodo dentro del árbol. Solo se emite en el editor, para actualizar la visibilidad de los nodos deshabilitados.
Enumeraciones
enum GroupCallFlags: 🔗
GroupCallFlags GROUP_CALL_DEFAULT = 0
Call nodes within a group with no special behavior (default).
GroupCallFlags GROUP_CALL_REVERSE = 1
Llama a los nodos dentro de un grupo en orden jerárquico inverso al del árbol (todos los hijos anidados son llamados antes que sus respectivos nodos padres).
GroupCallFlags GROUP_CALL_DEFERRED = 2
Call nodes within a group at the end of the current frame (can be either process or physics frame), similar to Object.call_deferred().
GroupCallFlags GROUP_CALL_UNIQUE = 4
Llama a los nodos dentro de un grupo una sola vez, incluso si la llamada se ejecuta muchas veces en el mismo fotograma. Debe combinarse con GROUP_CALL_DEFERRED para que funcione.
Nota: Los argumentos diferentes no se tienen en cuenta. Por lo tanto, cuando la misma llamada se ejecuta con diferentes argumentos, solo se realizará la primera llamada.
Descripciones de Propiedades
bool auto_accept_quit = true 🔗
If true, the application automatically accepts quitting requests.
For mobile platforms, see quit_on_go_back.
El nodo raíz de la escena principal cargada actualmente, normalmente como hijo directo de root. Véase también change_scene_to_file(), change_scene_to_packed(), y reload_current_scene().
Advertencia: Establecer esta propiedad directamente puede no funcionar como se espera, ya que no añade ni elimina ningún nodo de este árbol.
bool debug_collisions_hint = false 🔗
Si es true, las formas de colisión serán visibles al ejecutar el juego desde el editor con fines de depuración.
Nota: Esta propiedad no está diseñada para ser cambiada en tiempo de ejecución. Cambiar el valor de debug_collisions_hint mientras el proyecto está en ejecución no tendrá el efecto deseado.
Si es true, los polígonos de navegación serán visibles al ejecutar el juego desde el editor con fines de depuración.
Nota: Esta propiedad no está diseñada para ser cambiada en tiempo de ejecución. Cambiar el valor de debug_navigation_hint mientras el proyecto está en ejecución no tendrá el efecto deseado.
bool debug_paths_hint = false 🔗
Si es true, las curvas de los nodos Path2D y Path3D serán visibles al ejecutar el juego desde el editor con fines de depuración.
Nota: Esta propiedad no está diseñada para ser cambiada en tiempo de ejecución. Cambiar el valor de debug_paths_hint mientras el proyecto está en ejecución no tendrá el efecto deseado.
La raíz de la escena que se está editando actualmente en el editor. Suele ser un hijo directo de root.
Nota: Esta propiedad no hace nada en las compilaciones de lanzamiento (release builds).
bool multiplayer_poll = true 🔗
If true (default value), enables automatic polling of the MultiplayerAPI for this SceneTree during process_frame.
If false, you need to manually call MultiplayerAPI.poll() to process network packets and deliver RPCs. This allows running RPCs in a different loop (e.g. physics, thread, specific time step) and for manual Mutex protection when accessing the MultiplayerAPI from threads.
If true, the scene tree is considered paused. This causes the following behavior:
2D and 3D physics will be stopped, as well as collision detection and related signals.
Depending on each node's Node.process_mode, their Node._process(), Node._physics_process() and Node._input() callback methods may not called anymore.
bool physics_interpolation = false 🔗
If true, the renderer will interpolate the transforms of objects (both physics and non-physics) between the last two transforms, so that smooth motion is seen even when physics ticks do not coincide with rendered frames.
The default value of this property is controlled by ProjectSettings.physics/common/physics_interpolation.
Note: Although this is a global setting, finer control of individual branches of the SceneTree is possible using Node.physics_interpolation_mode.
If true, the application quits automatically when navigating back (e.g. using the system "Back" button on Android).
To handle 'Go Back' button when this option is disabled, use DisplayServer.WINDOW_EVENT_GO_BACK_REQUEST.
Window get_root()
The tree's root Window. This is top-most Node of the scene tree, and is always present. An absolute NodePath always starts from this node. Children of the root node may include the loaded current_scene, as well as any AutoLoad configured in the Project Settings.
Warning: Do not delete this node. This will result in unstable behavior, followed by a crash.
Descripciones de Métodos
void call_group(group: StringName, method: StringName, ...) vararg 🔗
Calls method on each node inside this tree added to the given group. You can pass arguments to method by specifying them at the end of this method call. Nodes that cannot call method (either because the method doesn't exist or the arguments do not match) are ignored. See also set_group() and notify_group().
Note: This method acts immediately on all selected nodes at once, which may cause stuttering in some performance-intensive situations.
Note: In C#, method must be in snake_case when referring to built-in Godot methods. Prefer using the names exposed in the MethodName class to avoid allocating a new StringName on each call.
void call_group_flags(flags: int, group: StringName, method: StringName, ...) vararg 🔗
Calls the given method on each node inside this tree added to the given group. Use flags to customize this method's behavior (see GroupCallFlags). Additional arguments for method can be passed at the end of this method. Nodes that cannot call method (either because the method doesn't exist or the arguments do not match) are ignored.
# Calls "hide" to all nodes of the "enemies" group, at the end of the frame and in reverse tree order.
get_tree().call_group_flags(
SceneTree.GROUP_CALL_DEFERRED | SceneTree.GROUP_CALL_REVERSE,
"enemies", "hide")
Note: In C#, method must be in snake_case when referring to built-in Godot methods. Prefer using the names exposed in the MethodName class to avoid allocating a new StringName on each call.
Error change_scene_to_file(path: String) 🔗
Changes the running scene to the one at the given path, after loading it into a PackedScene and creating a new instance.
Returns @GlobalScope.OK on success, @GlobalScope.ERR_CANT_OPEN if the path cannot be loaded into a PackedScene, or @GlobalScope.ERR_CANT_CREATE if that scene cannot be instantiated.
Note: See change_scene_to_node() for details on the order of operations.
Error change_scene_to_node(node: Node) 🔗
Changes the running scene to the provided Node. Useful when you want to set up the new scene before changing.
Returns @GlobalScope.OK on success, @GlobalScope.ERR_INVALID_PARAMETER if the node is null, or @GlobalScope.ERR_UNCONFIGURED if the node is already inside the scene tree.
Note: Operations happen in the following order when change_scene_to_node() is called:
The current scene node is immediately removed from the tree. From that point, Node.get_tree() called on the current (outgoing) scene will return
null. current_scene will benulltoo, because the new scene is not available yet.At the end of the frame, the formerly current scene, already removed from the tree, will be deleted (freed from memory) and then the new scene node will be added to the tree. Node.get_tree() and current_scene will be back to working as usual.
This ensures that both scenes aren't running at the same time, while still freeing the previous scene in a safe way similar to Node.queue_free().
If you want to reliably access the new scene, await the scene_changed signal.
Warning: After using this method, the SceneTree will take ownership of the node and will free it automatically when changing scene again. Any references you had to that node will become invalid.
Error change_scene_to_packed(packed_scene: PackedScene) 🔗
Changes the running scene to a new instance of the given PackedScene (which must be valid).
Returns @GlobalScope.OK on success, @GlobalScope.ERR_CANT_CREATE if the scene cannot be instantiated, or @GlobalScope.ERR_INVALID_PARAMETER if the scene is invalid.
Note: See change_scene_to_node() for details on the order of operations.
SceneTreeTimer create_timer(time_sec: float, process_always: bool = true, process_in_physics: bool = false, ignore_time_scale: bool = false) 🔗
Returns a new SceneTreeTimer. After time_sec in seconds have passed, the timer will emit SceneTreeTimer.timeout and will be automatically freed.
If process_always is false, the timer will be paused when setting paused to true.
If process_in_physics is true, the timer will update at the end of the physics frame, instead of the process frame.
If ignore_time_scale is true, the timer will ignore Engine.time_scale and update with the real, elapsed time.
This method is commonly used to create a one-shot delay timer, as in the following example:
func some_function():
print("start")
await get_tree().create_timer(1.0).timeout
print("end")
public async Task SomeFunction()
{
GD.Print("start");
await ToSignal(GetTree().CreateTimer(1.0f), SceneTreeTimer.SignalName.Timeout);
GD.Print("end");
}
Note: The timer is always updated after all of the nodes in the tree. A node's Node._process() method would be called before the timer updates (or Node._physics_process() if process_in_physics is set to true).
Creates and returns a new Tween processed in this tree. The Tween will start automatically on the next process frame or physics frame (depending on its TweenProcessMode).
Note: A Tween created using this method is not bound to any Node. It may keep working until there is nothing left to animate. If you want the Tween to be automatically killed when the Node is freed, use Node.create_tween() or Tween.bind_node().
Node get_first_node_in_group(group: StringName) 🔗
Returns the first Node found inside the tree, that has been added to the given group, in scene hierarchy order. Returns null if no match is found. See also get_nodes_in_group().
Returns how many physics process steps have been processed, since the application started. This is not a measurement of elapsed time. See also physics_frame. For the number of frames rendered, see Engine.get_process_frames().
MultiplayerAPI get_multiplayer(for_path: NodePath = NodePath("")) const 🔗
Searches for the MultiplayerAPI configured for the given path, if one does not exist it searches the parent paths until one is found. If the path is empty, or none is found, the default one is returned. See set_multiplayer().
Devuelve el número de nodos dentro de este árbol.
int get_node_count_in_group(group: StringName) const 🔗
Devuelve el número de nodos asignados al grupo dado.
Array[Node] get_nodes_in_group(group: StringName) 🔗
Devuelve un Array que contiene todos los nodos dentro de este árbol, que han sido añadidos al group dado, en orden de jerarquía de escena.
Array[Tween] get_processed_tweens() 🔗
Devuelve un Array de los Tweens existentes en el árbol, incluyendo los tweens pausados.
bool has_group(name: StringName) const 🔗
Devuelve true si un nodo añadido al grupo name dado existe en el árbol.
bool is_accessibility_enabled() const 🔗
Devuelve true si las características de accesibilidad están habilitadas, y las actualizaciones de información de accesibilidad se procesan activamente.
bool is_accessibility_supported() const 🔗
Devuelve true si las funciones de accesibilidad son compatibles con el sistema operativo y están habilitadas en la configuración del proyecto.
void notify_group(group: StringName, notification: int) 🔗
Llama a Object.notification() con la notification dada a todos los nodos dentro de este árbol añadidos al group. Véase también Notificaciones de Godot y call_group() y set_group().
Nota: Este método actúa inmediatamente sobre todos los nodos seleccionados a la vez, lo que puede causar tartamudeo en algunas situaciones de rendimiento intensivo.
void notify_group_flags(call_flags: int, group: StringName, notification: int) 🔗
Llama a Object.notification() con la notification dada a todos los nodos dentro de este árbol añadidos al group. Usa call_flags para personalizar el comportamiento de este método (véase GroupCallFlags).
void queue_delete(obj: Object) 🔗
Pone en cola el obj dado para ser borrado, llamando a su Object.free() al final del fotograma actual. Este método es similar a Node.queue_free().
void quit(exit_code: int = 0) 🔗
Quits the application at the end of the current iteration, with the given exit_code.
By convention, an exit code of 0 indicates success, whereas any other exit code indicates an error. For portability reasons, it should be between 0 and 125 (inclusive).
Note: On iOS this method doesn't work. Instead, as recommended by the iOS Human Interface Guidelines, the user is expected to close apps via the Home button.
Error reload_current_scene() 🔗
Reloads the currently active scene, replacing current_scene with a new instance of its original PackedScene.
Returns @GlobalScope.OK on success, @GlobalScope.ERR_UNCONFIGURED if no current_scene is defined, @GlobalScope.ERR_CANT_OPEN if current_scene cannot be loaded into a PackedScene, or @GlobalScope.ERR_CANT_CREATE if the scene cannot be instantiated.
void set_group(group: StringName, property: String, value: Variant) 🔗
Sets the given property to value on all nodes inside this tree added to the given group. Nodes that do not have the property are ignored. See also call_group() and notify_group().
Note: This method acts immediately on all selected nodes at once, which may cause stuttering in some performance-intensive situations.
Note: In C#, property must be in snake_case when referring to built-in Godot properties. Prefer using the names exposed in the PropertyName class to avoid allocating a new StringName on each call.
void set_group_flags(call_flags: int, group: StringName, property: String, value: Variant) 🔗
Sets the given property to value on all nodes inside this tree added to the given group. Nodes that do not have the property are ignored. Use call_flags to customize this method's behavior (see GroupCallFlags).
Note: In C#, property must be in snake_case when referring to built-in Godot properties. Prefer using the names exposed in the PropertyName class to avoid allocating a new StringName on each call.
void set_multiplayer(multiplayer: MultiplayerAPI, root_path: NodePath = NodePath("")) 🔗
Sets a custom MultiplayerAPI with the given root_path (controlling also the relative subpaths), or override the default one if root_path is empty.
Note: No MultiplayerAPI must be configured for the subpath containing root_path, nested custom multiplayers are not allowed. I.e. if one is configured for "/root/Foo" setting one for "/root/Foo/Bar" will cause an error.
Note: set_multiplayer() should be called before the child nodes are ready at the given root_path. If multiplayer nodes like MultiplayerSpawner or MultiplayerSynchronizer are added to the tree before the custom multiplayer API is set, they will not work.
void unload_current_scene() 🔗
Si una escena actual está cargada, llamar a este método la descargará.